Expressions
Every AST node in SQLGlot is represented by a subclass of Expression.
This module contains the implementation of all supported Expression types. Additionally,
it exposes a number of helper functions, which are mainly used to programmatically build
SQL expressions, such as sqlglot.expressions.select.
1""" 2## Expressions 3 4Every AST node in SQLGlot is represented by a subclass of `Expression`. 5 6This module contains the implementation of all supported `Expression` types. Additionally, 7it exposes a number of helper functions, which are mainly used to programmatically build 8SQL expressions, such as `sqlglot.expressions.select`. 9 10---- 11""" 12 13from __future__ import annotations 14 15import datetime 16import math 17import numbers 18import re 19import typing as t 20from collections import deque 21from copy import deepcopy 22from enum import auto 23 24from sqlglot.errors import ParseError 25from sqlglot.helper import ( 26 AutoName, 27 camel_to_snake_case, 28 ensure_collection, 29 ensure_list, 30 seq_get, 31 split_num_words, 32 subclasses, 33) 34from sqlglot.tokens import Token 35 36if t.TYPE_CHECKING: 37 from sqlglot.dialects.dialect import DialectType 38 39E = t.TypeVar("E", bound="Expression") 40 41 42class _Expression(type): 43 def __new__(cls, clsname, bases, attrs): 44 klass = super().__new__(cls, clsname, bases, attrs) 45 46 # When an Expression class is created, its key is automatically set to be 47 # the lowercase version of the class' name. 48 klass.key = clsname.lower() 49 50 # This is so that docstrings are not inherited in pdoc 51 klass.__doc__ = klass.__doc__ or "" 52 53 return klass 54 55 56class Expression(metaclass=_Expression): 57 """ 58 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 59 context, such as its child expressions, their names (arg keys), and whether a given child expression 60 is optional or not. 61 62 Attributes: 63 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 64 and representing expressions as strings. 65 arg_types: determines what arguments (child nodes) are supported by an expression. It 66 maps arg keys to booleans that indicate whether the corresponding args are optional. 67 68 Example: 69 >>> class Foo(Expression): 70 ... arg_types = {"this": True, "expression": False} 71 72 The above definition informs us that Foo is an Expression that requires an argument called 73 "this" and may also optionally receive an argument called "expression". 74 75 Args: 76 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 77 parent: a reference to the parent expression (or None, in case of root expressions). 78 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 79 uses to refer to it. 80 comments: a list of comments that are associated with a given expression. This is used in 81 order to preserve comments when transpiling SQL code. 82 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 83 optimizer, in order to enable some transformations that require type information. 84 """ 85 86 key = "expression" 87 arg_types = {"this": True} 88 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 89 90 def __init__(self, **args: t.Any): 91 self.args: t.Dict[str, t.Any] = args 92 self.parent: t.Optional[Expression] = None 93 self.arg_key: t.Optional[str] = None 94 self.comments: t.Optional[t.List[str]] = None 95 self._type: t.Optional[DataType] = None 96 self._meta: t.Optional[t.Dict[str, t.Any]] = None 97 self._hash: t.Optional[int] = None 98 99 for arg_key, value in self.args.items(): 100 self._set_parent(arg_key, value) 101 102 def __eq__(self, other) -> bool: 103 return type(self) is type(other) and hash(self) == hash(other) 104 105 @property 106 def hashable_args(self) -> t.Any: 107 args = (self.args.get(k) for k in self.arg_types) 108 109 return tuple( 110 (tuple(_norm_arg(a) for a in arg) if arg else None) 111 if type(arg) is list 112 else (_norm_arg(arg) if arg is not None and arg is not False else None) 113 for arg in args 114 ) 115 116 def __hash__(self) -> int: 117 if self._hash is not None: 118 return self._hash 119 120 return hash((self.__class__, self.hashable_args)) 121 122 @property 123 def this(self): 124 """ 125 Retrieves the argument with key "this". 126 """ 127 return self.args.get("this") 128 129 @property 130 def expression(self): 131 """ 132 Retrieves the argument with key "expression". 133 """ 134 return self.args.get("expression") 135 136 @property 137 def expressions(self): 138 """ 139 Retrieves the argument with key "expressions". 140 """ 141 return self.args.get("expressions") or [] 142 143 def text(self, key) -> str: 144 """ 145 Returns a textual representation of the argument corresponding to "key". This can only be used 146 for args that are strings or leaf Expression instances, such as identifiers and literals. 147 """ 148 field = self.args.get(key) 149 if isinstance(field, str): 150 return field 151 if isinstance(field, (Identifier, Literal, Var)): 152 return field.this 153 if isinstance(field, (Star, Null)): 154 return field.name 155 return "" 156 157 @property 158 def is_string(self) -> bool: 159 """ 160 Checks whether a Literal expression is a string. 161 """ 162 return isinstance(self, Literal) and self.args["is_string"] 163 164 @property 165 def is_number(self) -> bool: 166 """ 167 Checks whether a Literal expression is a number. 168 """ 169 return isinstance(self, Literal) and not self.args["is_string"] 170 171 @property 172 def is_int(self) -> bool: 173 """ 174 Checks whether a Literal expression is an integer. 175 """ 176 if self.is_number: 177 try: 178 int(self.name) 179 return True 180 except ValueError: 181 pass 182 return False 183 184 @property 185 def is_star(self) -> bool: 186 """Checks whether an expression is a star.""" 187 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 188 189 @property 190 def alias(self) -> str: 191 """ 192 Returns the alias of the expression, or an empty string if it's not aliased. 193 """ 194 if isinstance(self.args.get("alias"), TableAlias): 195 return self.args["alias"].name 196 return self.text("alias") 197 198 @property 199 def name(self) -> str: 200 return self.text("this") 201 202 @property 203 def alias_or_name(self): 204 return self.alias or self.name 205 206 @property 207 def output_name(self): 208 """ 209 Name of the output column if this expression is a selection. 210 211 If the Expression has no output name, an empty string is returned. 212 213 Example: 214 >>> from sqlglot import parse_one 215 >>> parse_one("SELECT a").expressions[0].output_name 216 'a' 217 >>> parse_one("SELECT b AS c").expressions[0].output_name 218 'c' 219 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 220 '' 221 """ 222 return "" 223 224 @property 225 def type(self) -> t.Optional[DataType]: 226 return self._type 227 228 @type.setter 229 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 230 if dtype and not isinstance(dtype, DataType): 231 dtype = DataType.build(dtype) 232 self._type = dtype # type: ignore 233 234 @property 235 def meta(self) -> t.Dict[str, t.Any]: 236 if self._meta is None: 237 self._meta = {} 238 return self._meta 239 240 def __deepcopy__(self, memo): 241 copy = self.__class__(**deepcopy(self.args)) 242 if self.comments is not None: 243 copy.comments = deepcopy(self.comments) 244 245 if self._type is not None: 246 copy._type = self._type.copy() 247 248 if self._meta is not None: 249 copy._meta = deepcopy(self._meta) 250 251 return copy 252 253 def copy(self): 254 """ 255 Returns a deep copy of the expression. 256 """ 257 new = deepcopy(self) 258 new.parent = self.parent 259 return new 260 261 def append(self, arg_key, value): 262 """ 263 Appends value to arg_key if it's a list or sets it as a new list. 264 265 Args: 266 arg_key (str): name of the list expression arg 267 value (Any): value to append to the list 268 """ 269 if not isinstance(self.args.get(arg_key), list): 270 self.args[arg_key] = [] 271 self.args[arg_key].append(value) 272 self._set_parent(arg_key, value) 273 274 def set(self, arg_key, value): 275 """ 276 Sets `arg_key` to `value`. 277 278 Args: 279 arg_key (str): name of the expression arg. 280 value: value to set the arg to. 281 """ 282 self.args[arg_key] = value 283 self._set_parent(arg_key, value) 284 285 def _set_parent(self, arg_key, value): 286 if hasattr(value, "parent"): 287 value.parent = self 288 value.arg_key = arg_key 289 elif type(value) is list: 290 for v in value: 291 if hasattr(v, "parent"): 292 v.parent = self 293 v.arg_key = arg_key 294 295 @property 296 def depth(self): 297 """ 298 Returns the depth of this tree. 299 """ 300 if self.parent: 301 return self.parent.depth + 1 302 return 0 303 304 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 305 """Yields the key and expression for all arguments, exploding list args.""" 306 for k, vs in self.args.items(): 307 if type(vs) is list: 308 for v in vs: 309 if hasattr(v, "parent"): 310 yield k, v 311 else: 312 if hasattr(vs, "parent"): 313 yield k, vs 314 315 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 316 """ 317 Returns the first node in this tree which matches at least one of 318 the specified types. 319 320 Args: 321 expression_types: the expression type(s) to match. 322 323 Returns: 324 The node which matches the criteria or None if no such node was found. 325 """ 326 return next(self.find_all(*expression_types, bfs=bfs), None) 327 328 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 329 """ 330 Returns a generator object which visits all nodes in this tree and only 331 yields those that match at least one of the specified expression types. 332 333 Args: 334 expression_types: the expression type(s) to match. 335 336 Returns: 337 The generator object. 338 """ 339 for expression, *_ in self.walk(bfs=bfs): 340 if isinstance(expression, expression_types): 341 yield expression 342 343 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 344 """ 345 Returns a nearest parent matching expression_types. 346 347 Args: 348 expression_types: the expression type(s) to match. 349 350 Returns: 351 The parent node. 352 """ 353 ancestor = self.parent 354 while ancestor and not isinstance(ancestor, expression_types): 355 ancestor = ancestor.parent 356 return t.cast(E, ancestor) 357 358 @property 359 def parent_select(self): 360 """ 361 Returns the parent select statement. 362 """ 363 return self.find_ancestor(Select) 364 365 @property 366 def same_parent(self): 367 """Returns if the parent is the same class as itself.""" 368 return type(self.parent) is self.__class__ 369 370 def root(self) -> Expression: 371 """ 372 Returns the root expression of this tree. 373 """ 374 expression = self 375 while expression.parent: 376 expression = expression.parent 377 return expression 378 379 def walk(self, bfs=True, prune=None): 380 """ 381 Returns a generator object which visits all nodes in this tree. 382 383 Args: 384 bfs (bool): if set to True the BFS traversal order will be applied, 385 otherwise the DFS traversal will be used instead. 386 prune ((node, parent, arg_key) -> bool): callable that returns True if 387 the generator should stop traversing this branch of the tree. 388 389 Returns: 390 the generator object. 391 """ 392 if bfs: 393 yield from self.bfs(prune=prune) 394 else: 395 yield from self.dfs(prune=prune) 396 397 def dfs(self, parent=None, key=None, prune=None): 398 """ 399 Returns a generator object which visits all nodes in this tree in 400 the DFS (Depth-first) order. 401 402 Returns: 403 The generator object. 404 """ 405 parent = parent or self.parent 406 yield self, parent, key 407 if prune and prune(self, parent, key): 408 return 409 410 for k, v in self.iter_expressions(): 411 yield from v.dfs(self, k, prune) 412 413 def bfs(self, prune=None): 414 """ 415 Returns a generator object which visits all nodes in this tree in 416 the BFS (Breadth-first) order. 417 418 Returns: 419 The generator object. 420 """ 421 queue = deque([(self, self.parent, None)]) 422 423 while queue: 424 item, parent, key = queue.popleft() 425 426 yield item, parent, key 427 if prune and prune(item, parent, key): 428 continue 429 430 for k, v in item.iter_expressions(): 431 queue.append((v, item, k)) 432 433 def unnest(self): 434 """ 435 Returns the first non parenthesis child or self. 436 """ 437 expression = self 438 while type(expression) is Paren: 439 expression = expression.this 440 return expression 441 442 def unalias(self): 443 """ 444 Returns the inner expression if this is an Alias. 445 """ 446 if isinstance(self, Alias): 447 return self.this 448 return self 449 450 def unnest_operands(self): 451 """ 452 Returns unnested operands as a tuple. 453 """ 454 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 455 456 def flatten(self, unnest=True): 457 """ 458 Returns a generator which yields child nodes who's parents are the same class. 459 460 A AND B AND C -> [A, B, C] 461 """ 462 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 463 if not type(node) is self.__class__: 464 yield node.unnest() if unnest else node 465 466 def __str__(self): 467 return self.sql() 468 469 def __repr__(self): 470 return self._to_s() 471 472 def sql(self, dialect: DialectType = None, **opts) -> str: 473 """ 474 Returns SQL string representation of this tree. 475 476 Args: 477 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 478 opts: other `sqlglot.generator.Generator` options. 479 480 Returns: 481 The SQL string. 482 """ 483 from sqlglot.dialects import Dialect 484 485 return Dialect.get_or_raise(dialect)().generate(self, **opts) 486 487 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 488 indent = "" if not level else "\n" 489 indent += "".join([" "] * level) 490 left = f"({self.key.upper()} " 491 492 args: t.Dict[str, t.Any] = { 493 k: ", ".join( 494 v._to_s(hide_missing=hide_missing, level=level + 1) 495 if hasattr(v, "_to_s") 496 else str(v) 497 for v in ensure_list(vs) 498 if v is not None 499 ) 500 for k, vs in self.args.items() 501 } 502 args["comments"] = self.comments 503 args["type"] = self.type 504 args = {k: v for k, v in args.items() if v or not hide_missing} 505 506 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 507 right += ")" 508 509 return indent + left + right 510 511 def transform(self, fun, *args, copy=True, **kwargs): 512 """ 513 Recursively visits all tree nodes (excluding already transformed ones) 514 and applies the given transformation function to each node. 515 516 Args: 517 fun (function): a function which takes a node as an argument and returns a 518 new transformed node or the same node without modifications. If the function 519 returns None, then the corresponding node will be removed from the syntax tree. 520 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 521 modified in place. 522 523 Returns: 524 The transformed tree. 525 """ 526 node = self.copy() if copy else self 527 new_node = fun(node, *args, **kwargs) 528 529 if new_node is None or not isinstance(new_node, Expression): 530 return new_node 531 if new_node is not node: 532 new_node.parent = node.parent 533 return new_node 534 535 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 536 return new_node 537 538 def replace(self, expression): 539 """ 540 Swap out this expression with a new expression. 541 542 For example:: 543 544 >>> tree = Select().select("x").from_("tbl") 545 >>> tree.find(Column).replace(Column(this="y")) 546 (COLUMN this: y) 547 >>> tree.sql() 548 'SELECT y FROM tbl' 549 550 Args: 551 expression (Expression|None): new node 552 553 Returns: 554 The new expression or expressions. 555 """ 556 if not self.parent: 557 return expression 558 559 parent = self.parent 560 self.parent = None 561 562 replace_children(parent, lambda child: expression if child is self else child) 563 return expression 564 565 def pop(self): 566 """ 567 Remove this expression from its AST. 568 569 Returns: 570 The popped expression. 571 """ 572 self.replace(None) 573 return self 574 575 def assert_is(self, type_): 576 """ 577 Assert that this `Expression` is an instance of `type_`. 578 579 If it is NOT an instance of `type_`, this raises an assertion error. 580 Otherwise, this returns this expression. 581 582 Examples: 583 This is useful for type security in chained expressions: 584 585 >>> import sqlglot 586 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 587 'SELECT x, z FROM y' 588 """ 589 assert isinstance(self, type_) 590 return self 591 592 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 593 """ 594 Checks if this expression is valid (e.g. all mandatory args are set). 595 596 Args: 597 args: a sequence of values that were used to instantiate a Func expression. This is used 598 to check that the provided arguments don't exceed the function argument limit. 599 600 Returns: 601 A list of error messages for all possible errors that were found. 602 """ 603 errors: t.List[str] = [] 604 605 for k in self.args: 606 if k not in self.arg_types: 607 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 608 for k, mandatory in self.arg_types.items(): 609 v = self.args.get(k) 610 if mandatory and (v is None or (isinstance(v, list) and not v)): 611 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 612 613 if ( 614 args 615 and isinstance(self, Func) 616 and len(args) > len(self.arg_types) 617 and not self.is_var_len_args 618 ): 619 errors.append( 620 f"The number of provided arguments ({len(args)}) is greater than " 621 f"the maximum number of supported arguments ({len(self.arg_types)})" 622 ) 623 624 return errors 625 626 def dump(self): 627 """ 628 Dump this Expression to a JSON-serializable dict. 629 """ 630 from sqlglot.serde import dump 631 632 return dump(self) 633 634 @classmethod 635 def load(cls, obj): 636 """ 637 Load a dict (as returned by `Expression.dump`) into an Expression instance. 638 """ 639 from sqlglot.serde import load 640 641 return load(obj) 642 643 644IntoType = t.Union[ 645 str, 646 t.Type[Expression], 647 t.Collection[t.Union[str, t.Type[Expression]]], 648] 649ExpOrStr = t.Union[str, Expression] 650 651 652class Condition(Expression): 653 def and_(self, *expressions, dialect=None, **opts): 654 """ 655 AND this condition with one or multiple expressions. 656 657 Example: 658 >>> condition("x=1").and_("y=1").sql() 659 'x = 1 AND y = 1' 660 661 Args: 662 *expressions (str | Expression): the SQL code strings to parse. 663 If an `Expression` instance is passed, it will be used as-is. 664 dialect (str): the dialect used to parse the input expression. 665 opts (kwargs): other options to use to parse the input expressions. 666 667 Returns: 668 And: the new condition. 669 """ 670 return and_(self, *expressions, dialect=dialect, **opts) 671 672 def or_(self, *expressions, dialect=None, **opts): 673 """ 674 OR this condition with one or multiple expressions. 675 676 Example: 677 >>> condition("x=1").or_("y=1").sql() 678 'x = 1 OR y = 1' 679 680 Args: 681 *expressions (str | Expression): the SQL code strings to parse. 682 If an `Expression` instance is passed, it will be used as-is. 683 dialect (str): the dialect used to parse the input expression. 684 opts (kwargs): other options to use to parse the input expressions. 685 686 Returns: 687 Or: the new condition. 688 """ 689 return or_(self, *expressions, dialect=dialect, **opts) 690 691 def not_(self): 692 """ 693 Wrap this condition with NOT. 694 695 Example: 696 >>> condition("x=1").not_().sql() 697 'NOT x = 1' 698 699 Returns: 700 Not: the new condition. 701 """ 702 return not_(self) 703 704 705class Predicate(Condition): 706 """Relationships like x = y, x > 1, x >= y.""" 707 708 709class DerivedTable(Expression): 710 @property 711 def alias_column_names(self): 712 table_alias = self.args.get("alias") 713 if not table_alias: 714 return [] 715 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 716 return [c.name for c in column_list] 717 718 @property 719 def selects(self): 720 alias = self.args.get("alias") 721 722 if alias: 723 return alias.columns 724 return [] 725 726 @property 727 def named_selects(self): 728 return [select.output_name for select in self.selects] 729 730 731class Unionable(Expression): 732 def union(self, expression, distinct=True, dialect=None, **opts): 733 """ 734 Builds a UNION expression. 735 736 Example: 737 >>> import sqlglot 738 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 739 'SELECT * FROM foo UNION SELECT * FROM bla' 740 741 Args: 742 expression (str | Expression): the SQL code string. 743 If an `Expression` instance is passed, it will be used as-is. 744 distinct (bool): set the DISTINCT flag if and only if this is true. 745 dialect (str): the dialect used to parse the input expression. 746 opts (kwargs): other options to use to parse the input expressions. 747 Returns: 748 Union: the Union expression. 749 """ 750 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 751 752 def intersect(self, expression, distinct=True, dialect=None, **opts): 753 """ 754 Builds an INTERSECT expression. 755 756 Example: 757 >>> import sqlglot 758 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 759 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 760 761 Args: 762 expression (str | Expression): the SQL code string. 763 If an `Expression` instance is passed, it will be used as-is. 764 distinct (bool): set the DISTINCT flag if and only if this is true. 765 dialect (str): the dialect used to parse the input expression. 766 opts (kwargs): other options to use to parse the input expressions. 767 Returns: 768 Intersect: the Intersect expression 769 """ 770 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 771 772 def except_(self, expression, distinct=True, dialect=None, **opts): 773 """ 774 Builds an EXCEPT expression. 775 776 Example: 777 >>> import sqlglot 778 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 779 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 780 781 Args: 782 expression (str | Expression): the SQL code string. 783 If an `Expression` instance is passed, it will be used as-is. 784 distinct (bool): set the DISTINCT flag if and only if this is true. 785 dialect (str): the dialect used to parse the input expression. 786 opts (kwargs): other options to use to parse the input expressions. 787 Returns: 788 Except: the Except expression 789 """ 790 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 791 792 793class UDTF(DerivedTable, Unionable): 794 pass 795 796 797class Cache(Expression): 798 arg_types = { 799 "with": False, 800 "this": True, 801 "lazy": False, 802 "options": False, 803 "expression": False, 804 } 805 806 807class Uncache(Expression): 808 arg_types = {"this": True, "exists": False} 809 810 811class Create(Expression): 812 arg_types = { 813 "with": False, 814 "this": True, 815 "kind": True, 816 "expression": False, 817 "exists": False, 818 "properties": False, 819 "replace": False, 820 "unique": False, 821 "indexes": False, 822 "no_schema_binding": False, 823 "begin": False, 824 } 825 826 827class Describe(Expression): 828 arg_types = {"this": True, "kind": False} 829 830 831class Pragma(Expression): 832 pass 833 834 835class Set(Expression): 836 arg_types = {"expressions": False} 837 838 839class SetItem(Expression): 840 arg_types = { 841 "this": False, 842 "expressions": False, 843 "kind": False, 844 "collate": False, # MySQL SET NAMES statement 845 "global": False, 846 } 847 848 849class Show(Expression): 850 arg_types = { 851 "this": True, 852 "target": False, 853 "offset": False, 854 "limit": False, 855 "like": False, 856 "where": False, 857 "db": False, 858 "full": False, 859 "mutex": False, 860 "query": False, 861 "channel": False, 862 "global": False, 863 "log": False, 864 "position": False, 865 "types": False, 866 } 867 868 869class UserDefinedFunction(Expression): 870 arg_types = {"this": True, "expressions": False, "wrapped": False} 871 872 873class CharacterSet(Expression): 874 arg_types = {"this": True, "default": False} 875 876 877class With(Expression): 878 arg_types = {"expressions": True, "recursive": False} 879 880 @property 881 def recursive(self) -> bool: 882 return bool(self.args.get("recursive")) 883 884 885class WithinGroup(Expression): 886 arg_types = {"this": True, "expression": False} 887 888 889class CTE(DerivedTable): 890 arg_types = {"this": True, "alias": True} 891 892 893class TableAlias(Expression): 894 arg_types = {"this": False, "columns": False} 895 896 @property 897 def columns(self): 898 return self.args.get("columns") or [] 899 900 901class BitString(Condition): 902 pass 903 904 905class HexString(Condition): 906 pass 907 908 909class ByteString(Condition): 910 pass 911 912 913class Column(Condition): 914 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 915 916 @property 917 def table(self) -> str: 918 return self.text("table") 919 920 @property 921 def db(self) -> str: 922 return self.text("db") 923 924 @property 925 def catalog(self) -> str: 926 return self.text("catalog") 927 928 @property 929 def output_name(self) -> str: 930 return self.name 931 932 @property 933 def parts(self) -> t.List[Identifier]: 934 """Return the parts of a column in order catalog, db, table, name.""" 935 return [part for part in reversed(list(self.args.values())) if part] 936 937 def to_dot(self) -> Dot: 938 """Converts the column into a dot expression.""" 939 parts = self.parts 940 parent = self.parent 941 942 while parent: 943 if isinstance(parent, Dot): 944 parts.append(parent.expression) 945 parent = parent.parent 946 947 return Dot.build(parts) 948 949 950class ColumnPosition(Expression): 951 arg_types = {"this": False, "position": True} 952 953 954class ColumnDef(Expression): 955 arg_types = { 956 "this": True, 957 "kind": False, 958 "constraints": False, 959 "exists": False, 960 "position": False, 961 } 962 963 964class AlterColumn(Expression): 965 arg_types = { 966 "this": True, 967 "dtype": False, 968 "collate": False, 969 "using": False, 970 "default": False, 971 "drop": False, 972 } 973 974 975class RenameTable(Expression): 976 pass 977 978 979class SetTag(Expression): 980 arg_types = {"expressions": True, "unset": False} 981 982 983class Comment(Expression): 984 arg_types = {"this": True, "kind": True, "expression": True, "exists": False} 985 986 987class ColumnConstraint(Expression): 988 arg_types = {"this": False, "kind": True} 989 990 991class ColumnConstraintKind(Expression): 992 pass 993 994 995class AutoIncrementColumnConstraint(ColumnConstraintKind): 996 pass 997 998 999class CaseSpecificColumnConstraint(ColumnConstraintKind): 1000 arg_types = {"not_": True} 1001 1002 1003class CharacterSetColumnConstraint(ColumnConstraintKind): 1004 arg_types = {"this": True} 1005 1006 1007class CheckColumnConstraint(ColumnConstraintKind): 1008 pass 1009 1010 1011class CollateColumnConstraint(ColumnConstraintKind): 1012 pass 1013 1014 1015class CommentColumnConstraint(ColumnConstraintKind): 1016 pass 1017 1018 1019class CompressColumnConstraint(ColumnConstraintKind): 1020 pass 1021 1022 1023class DateFormatColumnConstraint(ColumnConstraintKind): 1024 arg_types = {"this": True} 1025 1026 1027class DefaultColumnConstraint(ColumnConstraintKind): 1028 pass 1029 1030 1031class EncodeColumnConstraint(ColumnConstraintKind): 1032 pass 1033 1034 1035class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1036 # this: True -> ALWAYS, this: False -> BY DEFAULT 1037 arg_types = { 1038 "this": False, 1039 "start": False, 1040 "increment": False, 1041 "minvalue": False, 1042 "maxvalue": False, 1043 "cycle": False, 1044 } 1045 1046 1047class InlineLengthColumnConstraint(ColumnConstraintKind): 1048 pass 1049 1050 1051class NotNullColumnConstraint(ColumnConstraintKind): 1052 arg_types = {"allow_null": False} 1053 1054 1055# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html 1056class OnUpdateColumnConstraint(ColumnConstraintKind): 1057 pass 1058 1059 1060class PrimaryKeyColumnConstraint(ColumnConstraintKind): 1061 arg_types = {"desc": False} 1062 1063 1064class TitleColumnConstraint(ColumnConstraintKind): 1065 pass 1066 1067 1068class UniqueColumnConstraint(ColumnConstraintKind): 1069 arg_types: t.Dict[str, t.Any] = {} 1070 1071 1072class UppercaseColumnConstraint(ColumnConstraintKind): 1073 arg_types: t.Dict[str, t.Any] = {} 1074 1075 1076class PathColumnConstraint(ColumnConstraintKind): 1077 pass 1078 1079 1080class Constraint(Expression): 1081 arg_types = {"this": True, "expressions": True} 1082 1083 1084class Delete(Expression): 1085 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1086 1087 def delete( 1088 self, 1089 table: ExpOrStr, 1090 dialect: DialectType = None, 1091 copy: bool = True, 1092 **opts, 1093 ) -> Delete: 1094 """ 1095 Create a DELETE expression or replace the table on an existing DELETE expression. 1096 1097 Example: 1098 >>> delete("tbl").sql() 1099 'DELETE FROM tbl' 1100 1101 Args: 1102 table: the table from which to delete. 1103 dialect: the dialect used to parse the input expression. 1104 copy: if `False`, modify this expression instance in-place. 1105 opts: other options to use to parse the input expressions. 1106 1107 Returns: 1108 Delete: the modified expression. 1109 """ 1110 return _apply_builder( 1111 expression=table, 1112 instance=self, 1113 arg="this", 1114 dialect=dialect, 1115 into=Table, 1116 copy=copy, 1117 **opts, 1118 ) 1119 1120 def where( 1121 self, 1122 *expressions: ExpOrStr, 1123 append: bool = True, 1124 dialect: DialectType = None, 1125 copy: bool = True, 1126 **opts, 1127 ) -> Delete: 1128 """ 1129 Append to or set the WHERE expressions. 1130 1131 Example: 1132 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1133 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1134 1135 Args: 1136 *expressions: the SQL code strings to parse. 1137 If an `Expression` instance is passed, it will be used as-is. 1138 Multiple expressions are combined with an AND operator. 1139 append: if `True`, AND the new expressions to any existing expression. 1140 Otherwise, this resets the expression. 1141 dialect: the dialect used to parse the input expressions. 1142 copy: if `False`, modify this expression instance in-place. 1143 opts: other options to use to parse the input expressions. 1144 1145 Returns: 1146 Delete: the modified expression. 1147 """ 1148 return _apply_conjunction_builder( 1149 *expressions, 1150 instance=self, 1151 arg="where", 1152 append=append, 1153 into=Where, 1154 dialect=dialect, 1155 copy=copy, 1156 **opts, 1157 ) 1158 1159 def returning( 1160 self, 1161 expression: ExpOrStr, 1162 dialect: DialectType = None, 1163 copy: bool = True, 1164 **opts, 1165 ) -> Delete: 1166 """ 1167 Set the RETURNING expression. Not supported by all dialects. 1168 1169 Example: 1170 >>> delete("tbl").returning("*", dialect="postgres").sql() 1171 'DELETE FROM tbl RETURNING *' 1172 1173 Args: 1174 expression: the SQL code strings to parse. 1175 If an `Expression` instance is passed, it will be used as-is. 1176 dialect: the dialect used to parse the input expressions. 1177 copy: if `False`, modify this expression instance in-place. 1178 opts: other options to use to parse the input expressions. 1179 1180 Returns: 1181 Delete: the modified expression. 1182 """ 1183 return _apply_builder( 1184 expression=expression, 1185 instance=self, 1186 arg="returning", 1187 prefix="RETURNING", 1188 dialect=dialect, 1189 copy=copy, 1190 into=Returning, 1191 **opts, 1192 ) 1193 1194 1195class Drop(Expression): 1196 arg_types = { 1197 "this": False, 1198 "kind": False, 1199 "exists": False, 1200 "temporary": False, 1201 "materialized": False, 1202 "cascade": False, 1203 "constraints": False, 1204 "purge": False, 1205 } 1206 1207 1208class Filter(Expression): 1209 arg_types = {"this": True, "expression": True} 1210 1211 1212class Check(Expression): 1213 pass 1214 1215 1216class Directory(Expression): 1217 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1218 arg_types = {"this": True, "local": False, "row_format": False} 1219 1220 1221class ForeignKey(Expression): 1222 arg_types = { 1223 "expressions": True, 1224 "reference": False, 1225 "delete": False, 1226 "update": False, 1227 } 1228 1229 1230class PrimaryKey(Expression): 1231 arg_types = {"expressions": True, "options": False} 1232 1233 1234class Unique(Expression): 1235 arg_types = {"expressions": True} 1236 1237 1238# https://www.postgresql.org/docs/9.1/sql-selectinto.html 1239# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples 1240class Into(Expression): 1241 arg_types = {"this": True, "temporary": False, "unlogged": False} 1242 1243 1244class From(Expression): 1245 arg_types = {"expressions": True} 1246 1247 1248class Having(Expression): 1249 pass 1250 1251 1252class Hint(Expression): 1253 arg_types = {"expressions": True} 1254 1255 1256class JoinHint(Expression): 1257 arg_types = {"this": True, "expressions": True} 1258 1259 1260class Identifier(Expression): 1261 arg_types = {"this": True, "quoted": False} 1262 1263 @property 1264 def quoted(self): 1265 return bool(self.args.get("quoted")) 1266 1267 @property 1268 def hashable_args(self) -> t.Any: 1269 if self.quoted and any(char.isupper() for char in self.this): 1270 return (self.this, self.quoted) 1271 return self.this.lower() 1272 1273 @property 1274 def output_name(self): 1275 return self.name 1276 1277 1278class Index(Expression): 1279 arg_types = { 1280 "this": False, 1281 "table": False, 1282 "where": False, 1283 "columns": False, 1284 "unique": False, 1285 "primary": False, 1286 "amp": False, # teradata 1287 } 1288 1289 1290class Insert(Expression): 1291 arg_types = { 1292 "with": False, 1293 "this": True, 1294 "expression": False, 1295 "returning": False, 1296 "overwrite": False, 1297 "exists": False, 1298 "partition": False, 1299 "alternative": False, 1300 } 1301 1302 1303class Returning(Expression): 1304 arg_types = {"expressions": True} 1305 1306 1307# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html 1308class Introducer(Expression): 1309 arg_types = {"this": True, "expression": True} 1310 1311 1312# national char, like n'utf8' 1313class National(Expression): 1314 pass 1315 1316 1317class LoadData(Expression): 1318 arg_types = { 1319 "this": True, 1320 "local": False, 1321 "overwrite": False, 1322 "inpath": True, 1323 "partition": False, 1324 "input_format": False, 1325 "serde": False, 1326 } 1327 1328 1329class Partition(Expression): 1330 arg_types = {"expressions": True} 1331 1332 1333class Fetch(Expression): 1334 arg_types = { 1335 "direction": False, 1336 "count": False, 1337 "percent": False, 1338 "with_ties": False, 1339 } 1340 1341 1342class Group(Expression): 1343 arg_types = { 1344 "expressions": False, 1345 "grouping_sets": False, 1346 "cube": False, 1347 "rollup": False, 1348 } 1349 1350 1351class Lambda(Expression): 1352 arg_types = {"this": True, "expressions": True} 1353 1354 1355class Limit(Expression): 1356 arg_types = {"this": False, "expression": True} 1357 1358 1359class Literal(Condition): 1360 arg_types = {"this": True, "is_string": True} 1361 1362 @property 1363 def hashable_args(self) -> t.Any: 1364 return (self.this, self.args.get("is_string")) 1365 1366 @classmethod 1367 def number(cls, number) -> Literal: 1368 return cls(this=str(number), is_string=False) 1369 1370 @classmethod 1371 def string(cls, string) -> Literal: 1372 return cls(this=str(string), is_string=True) 1373 1374 @property 1375 def output_name(self): 1376 return self.name 1377 1378 1379class Join(Expression): 1380 arg_types = { 1381 "this": True, 1382 "on": False, 1383 "side": False, 1384 "kind": False, 1385 "using": False, 1386 "natural": False, 1387 "hint": False, 1388 } 1389 1390 @property 1391 def kind(self): 1392 return self.text("kind").upper() 1393 1394 @property 1395 def side(self): 1396 return self.text("side").upper() 1397 1398 @property 1399 def hint(self): 1400 return self.text("hint").upper() 1401 1402 @property 1403 def alias_or_name(self): 1404 return self.this.alias_or_name 1405 1406 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1407 """ 1408 Append to or set the ON expressions. 1409 1410 Example: 1411 >>> import sqlglot 1412 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1413 'JOIN x ON y = 1' 1414 1415 Args: 1416 *expressions (str | Expression): the SQL code strings to parse. 1417 If an `Expression` instance is passed, it will be used as-is. 1418 Multiple expressions are combined with an AND operator. 1419 append (bool): if `True`, AND the new expressions to any existing expression. 1420 Otherwise, this resets the expression. 1421 dialect (str): the dialect used to parse the input expressions. 1422 copy (bool): if `False`, modify this expression instance in-place. 1423 opts (kwargs): other options to use to parse the input expressions. 1424 1425 Returns: 1426 Join: the modified join expression. 1427 """ 1428 join = _apply_conjunction_builder( 1429 *expressions, 1430 instance=self, 1431 arg="on", 1432 append=append, 1433 dialect=dialect, 1434 copy=copy, 1435 **opts, 1436 ) 1437 1438 if join.kind == "CROSS": 1439 join.set("kind", None) 1440 1441 return join 1442 1443 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1444 """ 1445 Append to or set the USING expressions. 1446 1447 Example: 1448 >>> import sqlglot 1449 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1450 'JOIN x USING (foo, bla)' 1451 1452 Args: 1453 *expressions (str | Expression): the SQL code strings to parse. 1454 If an `Expression` instance is passed, it will be used as-is. 1455 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1456 Otherwise, this resets the expression. 1457 dialect (str): the dialect used to parse the input expressions. 1458 copy (bool): if `False`, modify this expression instance in-place. 1459 opts (kwargs): other options to use to parse the input expressions. 1460 1461 Returns: 1462 Join: the modified join expression. 1463 """ 1464 join = _apply_list_builder( 1465 *expressions, 1466 instance=self, 1467 arg="using", 1468 append=append, 1469 dialect=dialect, 1470 copy=copy, 1471 **opts, 1472 ) 1473 1474 if join.kind == "CROSS": 1475 join.set("kind", None) 1476 1477 return join 1478 1479 1480class Lateral(UDTF): 1481 arg_types = {"this": True, "view": False, "outer": False, "alias": False} 1482 1483 1484class MatchRecognize(Expression): 1485 arg_types = { 1486 "partition_by": False, 1487 "order": False, 1488 "measures": False, 1489 "rows": False, 1490 "after": False, 1491 "pattern": False, 1492 "define": False, 1493 "alias": False, 1494 } 1495 1496 1497# Clickhouse FROM FINAL modifier 1498# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier 1499class Final(Expression): 1500 pass 1501 1502 1503class Offset(Expression): 1504 arg_types = {"this": False, "expression": True} 1505 1506 1507class Order(Expression): 1508 arg_types = {"this": False, "expressions": True} 1509 1510 1511# hive specific sorts 1512# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy 1513class Cluster(Order): 1514 pass 1515 1516 1517class Distribute(Order): 1518 pass 1519 1520 1521class Sort(Order): 1522 pass 1523 1524 1525class Ordered(Expression): 1526 arg_types = {"this": True, "desc": True, "nulls_first": True} 1527 1528 1529class Property(Expression): 1530 arg_types = {"this": True, "value": True} 1531 1532 1533class AfterJournalProperty(Property): 1534 arg_types = {"no": True, "dual": False, "local": False} 1535 1536 1537class AlgorithmProperty(Property): 1538 arg_types = {"this": True} 1539 1540 1541class AutoIncrementProperty(Property): 1542 arg_types = {"this": True} 1543 1544 1545class BlockCompressionProperty(Property): 1546 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True} 1547 1548 1549class CharacterSetProperty(Property): 1550 arg_types = {"this": True, "default": True} 1551 1552 1553class ChecksumProperty(Property): 1554 arg_types = {"on": False, "default": False} 1555 1556 1557class CollateProperty(Property): 1558 arg_types = {"this": True} 1559 1560 1561class DataBlocksizeProperty(Property): 1562 arg_types = {"size": False, "units": False, "min": False, "default": False} 1563 1564 1565class DefinerProperty(Property): 1566 arg_types = {"this": True} 1567 1568 1569class DistKeyProperty(Property): 1570 arg_types = {"this": True} 1571 1572 1573class DistStyleProperty(Property): 1574 arg_types = {"this": True} 1575 1576 1577class EngineProperty(Property): 1578 arg_types = {"this": True} 1579 1580 1581class ExecuteAsProperty(Property): 1582 arg_types = {"this": True} 1583 1584 1585class ExternalProperty(Property): 1586 arg_types = {"this": False} 1587 1588 1589class FallbackProperty(Property): 1590 arg_types = {"no": True, "protection": False} 1591 1592 1593class FileFormatProperty(Property): 1594 arg_types = {"this": True} 1595 1596 1597class FreespaceProperty(Property): 1598 arg_types = {"this": True, "percent": False} 1599 1600 1601class InputOutputFormat(Expression): 1602 arg_types = {"input_format": False, "output_format": False} 1603 1604 1605class IsolatedLoadingProperty(Property): 1606 arg_types = { 1607 "no": True, 1608 "concurrent": True, 1609 "for_all": True, 1610 "for_insert": True, 1611 "for_none": True, 1612 } 1613 1614 1615class JournalProperty(Property): 1616 arg_types = {"no": True, "dual": False, "before": False} 1617 1618 1619class LanguageProperty(Property): 1620 arg_types = {"this": True} 1621 1622 1623class LikeProperty(Property): 1624 arg_types = {"this": True, "expressions": False} 1625 1626 1627class LocationProperty(Property): 1628 arg_types = {"this": True} 1629 1630 1631class LockingProperty(Property): 1632 arg_types = { 1633 "this": False, 1634 "kind": True, 1635 "for_or_in": True, 1636 "lock_type": True, 1637 "override": False, 1638 } 1639 1640 1641class LogProperty(Property): 1642 arg_types = {"no": True} 1643 1644 1645class MaterializedProperty(Property): 1646 arg_types = {"this": False} 1647 1648 1649class MergeBlockRatioProperty(Property): 1650 arg_types = {"this": False, "no": False, "default": False, "percent": False} 1651 1652 1653class NoPrimaryIndexProperty(Property): 1654 arg_types = {"this": False} 1655 1656 1657class OnCommitProperty(Property): 1658 arg_type = {"this": False} 1659 1660 1661class PartitionedByProperty(Property): 1662 arg_types = {"this": True} 1663 1664 1665class ReturnsProperty(Property): 1666 arg_types = {"this": True, "is_table": False, "table": False} 1667 1668 1669class RowFormatProperty(Property): 1670 arg_types = {"this": True} 1671 1672 1673class RowFormatDelimitedProperty(Property): 1674 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1675 arg_types = { 1676 "fields": False, 1677 "escaped": False, 1678 "collection_items": False, 1679 "map_keys": False, 1680 "lines": False, 1681 "null": False, 1682 "serde": False, 1683 } 1684 1685 1686class RowFormatSerdeProperty(Property): 1687 arg_types = {"this": True} 1688 1689 1690class SchemaCommentProperty(Property): 1691 arg_types = {"this": True} 1692 1693 1694class SerdeProperties(Property): 1695 arg_types = {"expressions": True} 1696 1697 1698class SetProperty(Property): 1699 arg_types = {"multi": True} 1700 1701 1702class SortKeyProperty(Property): 1703 arg_types = {"this": True, "compound": False} 1704 1705 1706class SqlSecurityProperty(Property): 1707 arg_types = {"definer": True} 1708 1709 1710class StabilityProperty(Property): 1711 arg_types = {"this": True} 1712 1713 1714class TableFormatProperty(Property): 1715 arg_types = {"this": True} 1716 1717 1718class TemporaryProperty(Property): 1719 arg_types = {"global_": True} 1720 1721 1722class TransientProperty(Property): 1723 arg_types = {"this": False} 1724 1725 1726class VolatileProperty(Property): 1727 arg_types = {"this": False} 1728 1729 1730class WithDataProperty(Property): 1731 arg_types = {"no": True, "statistics": False} 1732 1733 1734class WithJournalTableProperty(Property): 1735 arg_types = {"this": True} 1736 1737 1738class Properties(Expression): 1739 arg_types = {"expressions": True} 1740 1741 NAME_TO_PROPERTY = { 1742 "ALGORITHM": AlgorithmProperty, 1743 "AUTO_INCREMENT": AutoIncrementProperty, 1744 "CHARACTER SET": CharacterSetProperty, 1745 "COLLATE": CollateProperty, 1746 "COMMENT": SchemaCommentProperty, 1747 "DEFINER": DefinerProperty, 1748 "DISTKEY": DistKeyProperty, 1749 "DISTSTYLE": DistStyleProperty, 1750 "ENGINE": EngineProperty, 1751 "EXECUTE AS": ExecuteAsProperty, 1752 "FORMAT": FileFormatProperty, 1753 "LANGUAGE": LanguageProperty, 1754 "LOCATION": LocationProperty, 1755 "PARTITIONED_BY": PartitionedByProperty, 1756 "RETURNS": ReturnsProperty, 1757 "ROW_FORMAT": RowFormatProperty, 1758 "SORTKEY": SortKeyProperty, 1759 "TABLE_FORMAT": TableFormatProperty, 1760 } 1761 1762 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1763 1764 # CREATE property locations 1765 # Form: schema specified 1766 # create [POST_CREATE] 1767 # table a [POST_NAME] 1768 # (b int) [POST_SCHEMA] 1769 # with ([POST_WITH]) 1770 # index (b) [POST_INDEX] 1771 # 1772 # Form: alias selection 1773 # create [POST_CREATE] 1774 # table a [POST_NAME] 1775 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1776 # index (c) [POST_INDEX] 1777 class Location(AutoName): 1778 POST_CREATE = auto() 1779 POST_NAME = auto() 1780 POST_SCHEMA = auto() 1781 POST_WITH = auto() 1782 POST_ALIAS = auto() 1783 POST_EXPRESSION = auto() 1784 POST_INDEX = auto() 1785 UNSUPPORTED = auto() 1786 1787 @classmethod 1788 def from_dict(cls, properties_dict) -> Properties: 1789 expressions = [] 1790 for key, value in properties_dict.items(): 1791 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1792 if property_cls: 1793 expressions.append(property_cls(this=convert(value))) 1794 else: 1795 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1796 1797 return cls(expressions=expressions) 1798 1799 1800class Qualify(Expression): 1801 pass 1802 1803 1804# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql 1805class Return(Expression): 1806 pass 1807 1808 1809class Reference(Expression): 1810 arg_types = {"this": True, "expressions": False, "options": False} 1811 1812 1813class Tuple(Expression): 1814 arg_types = {"expressions": False} 1815 1816 1817class Subqueryable(Unionable): 1818 def subquery(self, alias=None, copy=True) -> Subquery: 1819 """ 1820 Convert this expression to an aliased expression that can be used as a Subquery. 1821 1822 Example: 1823 >>> subquery = Select().select("x").from_("tbl").subquery() 1824 >>> Select().select("x").from_(subquery).sql() 1825 'SELECT x FROM (SELECT x FROM tbl)' 1826 1827 Args: 1828 alias (str | Identifier): an optional alias for the subquery 1829 copy (bool): if `False`, modify this expression instance in-place. 1830 1831 Returns: 1832 Alias: the subquery 1833 """ 1834 instance = _maybe_copy(self, copy) 1835 return Subquery( 1836 this=instance, 1837 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1838 ) 1839 1840 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1841 raise NotImplementedError 1842 1843 @property 1844 def ctes(self): 1845 with_ = self.args.get("with") 1846 if not with_: 1847 return [] 1848 return with_.expressions 1849 1850 @property 1851 def selects(self): 1852 raise NotImplementedError("Subqueryable objects must implement `selects`") 1853 1854 @property 1855 def named_selects(self): 1856 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1857 1858 def with_( 1859 self, 1860 alias, 1861 as_, 1862 recursive=None, 1863 append=True, 1864 dialect=None, 1865 copy=True, 1866 **opts, 1867 ): 1868 """ 1869 Append to or set the common table expressions. 1870 1871 Example: 1872 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1873 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1874 1875 Args: 1876 alias (str | Expression): the SQL code string to parse as the table name. 1877 If an `Expression` instance is passed, this is used as-is. 1878 as_ (str | Expression): the SQL code string to parse as the table expression. 1879 If an `Expression` instance is passed, it will be used as-is. 1880 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1881 append (bool): if `True`, add to any existing expressions. 1882 Otherwise, this resets the expressions. 1883 dialect (str): the dialect used to parse the input expression. 1884 copy (bool): if `False`, modify this expression instance in-place. 1885 opts (kwargs): other options to use to parse the input expressions. 1886 1887 Returns: 1888 Select: the modified expression. 1889 """ 1890 alias_expression = maybe_parse( 1891 alias, 1892 dialect=dialect, 1893 into=TableAlias, 1894 **opts, 1895 ) 1896 as_expression = maybe_parse( 1897 as_, 1898 dialect=dialect, 1899 **opts, 1900 ) 1901 cte = CTE( 1902 this=as_expression, 1903 alias=alias_expression, 1904 ) 1905 return _apply_child_list_builder( 1906 cte, 1907 instance=self, 1908 arg="with", 1909 append=append, 1910 copy=copy, 1911 into=With, 1912 properties={"recursive": recursive or False}, 1913 ) 1914 1915 1916QUERY_MODIFIERS = { 1917 "match": False, 1918 "laterals": False, 1919 "joins": False, 1920 "pivots": False, 1921 "where": False, 1922 "group": False, 1923 "having": False, 1924 "qualify": False, 1925 "windows": False, 1926 "distribute": False, 1927 "sort": False, 1928 "cluster": False, 1929 "order": False, 1930 "limit": False, 1931 "offset": False, 1932 "lock": False, 1933 "sample": False, 1934} 1935 1936 1937class Table(Expression): 1938 arg_types = { 1939 "this": True, 1940 "alias": False, 1941 "db": False, 1942 "catalog": False, 1943 "laterals": False, 1944 "joins": False, 1945 "pivots": False, 1946 "hints": False, 1947 "system_time": False, 1948 } 1949 1950 @property 1951 def db(self) -> str: 1952 return self.text("db") 1953 1954 @property 1955 def catalog(self) -> str: 1956 return self.text("catalog") 1957 1958 1959# See the TSQL "Querying data in a system-versioned temporal table" page 1960class SystemTime(Expression): 1961 arg_types = { 1962 "this": False, 1963 "expression": False, 1964 "kind": True, 1965 } 1966 1967 1968class Union(Subqueryable): 1969 arg_types = { 1970 "with": False, 1971 "this": True, 1972 "expression": True, 1973 "distinct": False, 1974 **QUERY_MODIFIERS, 1975 } 1976 1977 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1978 """ 1979 Set the LIMIT expression. 1980 1981 Example: 1982 >>> select("1").union(select("1")).limit(1).sql() 1983 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1984 1985 Args: 1986 expression (str | int | Expression): the SQL code string to parse. 1987 This can also be an integer. 1988 If a `Limit` instance is passed, this is used as-is. 1989 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1990 dialect (str): the dialect used to parse the input expression. 1991 copy (bool): if `False`, modify this expression instance in-place. 1992 opts (kwargs): other options to use to parse the input expressions. 1993 1994 Returns: 1995 Select: The limited subqueryable. 1996 """ 1997 return ( 1998 select("*") 1999 .from_(self.subquery(alias="_l_0", copy=copy)) 2000 .limit(expression, dialect=dialect, copy=False, **opts) 2001 ) 2002 2003 def select( 2004 self, 2005 *expressions: ExpOrStr, 2006 append: bool = True, 2007 dialect: DialectType = None, 2008 copy: bool = True, 2009 **opts, 2010 ) -> Union: 2011 """Append to or set the SELECT of the union recursively. 2012 2013 Example: 2014 >>> from sqlglot import parse_one 2015 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2016 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2017 2018 Args: 2019 *expressions: the SQL code strings to parse. 2020 If an `Expression` instance is passed, it will be used as-is. 2021 append: if `True`, add to any existing expressions. 2022 Otherwise, this resets the expressions. 2023 dialect: the dialect used to parse the input expressions. 2024 copy: if `False`, modify this expression instance in-place. 2025 opts: other options to use to parse the input expressions. 2026 2027 Returns: 2028 Union: the modified expression. 2029 """ 2030 this = self.copy() if copy else self 2031 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2032 this.expression.unnest().select( 2033 *expressions, append=append, dialect=dialect, copy=False, **opts 2034 ) 2035 return this 2036 2037 @property 2038 def named_selects(self): 2039 return self.this.unnest().named_selects 2040 2041 @property 2042 def is_star(self) -> bool: 2043 return self.this.is_star or self.expression.is_star 2044 2045 @property 2046 def selects(self): 2047 return self.this.unnest().selects 2048 2049 @property 2050 def left(self): 2051 return self.this 2052 2053 @property 2054 def right(self): 2055 return self.expression 2056 2057 2058class Except(Union): 2059 pass 2060 2061 2062class Intersect(Union): 2063 pass 2064 2065 2066class Unnest(UDTF): 2067 arg_types = { 2068 "expressions": True, 2069 "ordinality": False, 2070 "alias": False, 2071 "offset": False, 2072 } 2073 2074 2075class Update(Expression): 2076 arg_types = { 2077 "with": False, 2078 "this": False, 2079 "expressions": True, 2080 "from": False, 2081 "where": False, 2082 "returning": False, 2083 } 2084 2085 2086class Values(UDTF): 2087 arg_types = { 2088 "expressions": True, 2089 "ordinality": False, 2090 "alias": False, 2091 } 2092 2093 2094class Var(Expression): 2095 pass 2096 2097 2098class Schema(Expression): 2099 arg_types = {"this": False, "expressions": False} 2100 2101 2102# Used to represent the FOR UPDATE and FOR SHARE locking read types. 2103# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html 2104class Lock(Expression): 2105 arg_types = {"update": True} 2106 2107 2108class Select(Subqueryable): 2109 arg_types = { 2110 "with": False, 2111 "kind": False, 2112 "expressions": False, 2113 "hint": False, 2114 "distinct": False, 2115 "into": False, 2116 "from": False, 2117 **QUERY_MODIFIERS, 2118 } 2119 2120 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2121 """ 2122 Set the FROM expression. 2123 2124 Example: 2125 >>> Select().from_("tbl").select("x").sql() 2126 'SELECT x FROM tbl' 2127 2128 Args: 2129 *expressions (str | Expression): the SQL code strings to parse. 2130 If a `From` instance is passed, this is used as-is. 2131 If another `Expression` instance is passed, it will be wrapped in a `From`. 2132 append (bool): if `True`, add to any existing expressions. 2133 Otherwise, this flattens all the `From` expression into a single expression. 2134 dialect (str): the dialect used to parse the input expression. 2135 copy (bool): if `False`, modify this expression instance in-place. 2136 opts (kwargs): other options to use to parse the input expressions. 2137 2138 Returns: 2139 Select: the modified expression. 2140 """ 2141 return _apply_child_list_builder( 2142 *expressions, 2143 instance=self, 2144 arg="from", 2145 append=append, 2146 copy=copy, 2147 prefix="FROM", 2148 into=From, 2149 dialect=dialect, 2150 **opts, 2151 ) 2152 2153 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2154 """ 2155 Set the GROUP BY expression. 2156 2157 Example: 2158 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2159 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2160 2161 Args: 2162 *expressions (str | Expression): the SQL code strings to parse. 2163 If a `Group` instance is passed, this is used as-is. 2164 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2165 If nothing is passed in then a group by is not applied to the expression 2166 append (bool): if `True`, add to any existing expressions. 2167 Otherwise, this flattens all the `Group` expression into a single expression. 2168 dialect (str): the dialect used to parse the input expression. 2169 copy (bool): if `False`, modify this expression instance in-place. 2170 opts (kwargs): other options to use to parse the input expressions. 2171 2172 Returns: 2173 Select: the modified expression. 2174 """ 2175 if not expressions: 2176 return self if not copy else self.copy() 2177 return _apply_child_list_builder( 2178 *expressions, 2179 instance=self, 2180 arg="group", 2181 append=append, 2182 copy=copy, 2183 prefix="GROUP BY", 2184 into=Group, 2185 dialect=dialect, 2186 **opts, 2187 ) 2188 2189 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2190 """ 2191 Set the ORDER BY expression. 2192 2193 Example: 2194 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2195 'SELECT x FROM tbl ORDER BY x DESC' 2196 2197 Args: 2198 *expressions (str | Expression): the SQL code strings to parse. 2199 If a `Group` instance is passed, this is used as-is. 2200 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2201 append (bool): if `True`, add to any existing expressions. 2202 Otherwise, this flattens all the `Order` expression into a single expression. 2203 dialect (str): the dialect used to parse the input expression. 2204 copy (bool): if `False`, modify this expression instance in-place. 2205 opts (kwargs): other options to use to parse the input expressions. 2206 2207 Returns: 2208 Select: the modified expression. 2209 """ 2210 return _apply_child_list_builder( 2211 *expressions, 2212 instance=self, 2213 arg="order", 2214 append=append, 2215 copy=copy, 2216 prefix="ORDER BY", 2217 into=Order, 2218 dialect=dialect, 2219 **opts, 2220 ) 2221 2222 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2223 """ 2224 Set the SORT BY expression. 2225 2226 Example: 2227 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2228 'SELECT x FROM tbl SORT BY x DESC' 2229 2230 Args: 2231 *expressions (str | Expression): the SQL code strings to parse. 2232 If a `Group` instance is passed, this is used as-is. 2233 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2234 append (bool): if `True`, add to any existing expressions. 2235 Otherwise, this flattens all the `Order` expression into a single expression. 2236 dialect (str): the dialect used to parse the input expression. 2237 copy (bool): if `False`, modify this expression instance in-place. 2238 opts (kwargs): other options to use to parse the input expressions. 2239 2240 Returns: 2241 Select: the modified expression. 2242 """ 2243 return _apply_child_list_builder( 2244 *expressions, 2245 instance=self, 2246 arg="sort", 2247 append=append, 2248 copy=copy, 2249 prefix="SORT BY", 2250 into=Sort, 2251 dialect=dialect, 2252 **opts, 2253 ) 2254 2255 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2256 """ 2257 Set the CLUSTER BY expression. 2258 2259 Example: 2260 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2261 'SELECT x FROM tbl CLUSTER BY x DESC' 2262 2263 Args: 2264 *expressions (str | Expression): the SQL code strings to parse. 2265 If a `Group` instance is passed, this is used as-is. 2266 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2267 append (bool): if `True`, add to any existing expressions. 2268 Otherwise, this flattens all the `Order` expression into a single expression. 2269 dialect (str): the dialect used to parse the input expression. 2270 copy (bool): if `False`, modify this expression instance in-place. 2271 opts (kwargs): other options to use to parse the input expressions. 2272 2273 Returns: 2274 Select: the modified expression. 2275 """ 2276 return _apply_child_list_builder( 2277 *expressions, 2278 instance=self, 2279 arg="cluster", 2280 append=append, 2281 copy=copy, 2282 prefix="CLUSTER BY", 2283 into=Cluster, 2284 dialect=dialect, 2285 **opts, 2286 ) 2287 2288 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2289 """ 2290 Set the LIMIT expression. 2291 2292 Example: 2293 >>> Select().from_("tbl").select("x").limit(10).sql() 2294 'SELECT x FROM tbl LIMIT 10' 2295 2296 Args: 2297 expression (str | int | Expression): the SQL code string to parse. 2298 This can also be an integer. 2299 If a `Limit` instance is passed, this is used as-is. 2300 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2301 dialect (str): the dialect used to parse the input expression. 2302 copy (bool): if `False`, modify this expression instance in-place. 2303 opts (kwargs): other options to use to parse the input expressions. 2304 2305 Returns: 2306 Select: the modified expression. 2307 """ 2308 return _apply_builder( 2309 expression=expression, 2310 instance=self, 2311 arg="limit", 2312 into=Limit, 2313 prefix="LIMIT", 2314 dialect=dialect, 2315 copy=copy, 2316 **opts, 2317 ) 2318 2319 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2320 """ 2321 Set the OFFSET expression. 2322 2323 Example: 2324 >>> Select().from_("tbl").select("x").offset(10).sql() 2325 'SELECT x FROM tbl OFFSET 10' 2326 2327 Args: 2328 expression (str | int | Expression): the SQL code string to parse. 2329 This can also be an integer. 2330 If a `Offset` instance is passed, this is used as-is. 2331 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2332 dialect (str): the dialect used to parse the input expression. 2333 copy (bool): if `False`, modify this expression instance in-place. 2334 opts (kwargs): other options to use to parse the input expressions. 2335 2336 Returns: 2337 Select: the modified expression. 2338 """ 2339 return _apply_builder( 2340 expression=expression, 2341 instance=self, 2342 arg="offset", 2343 into=Offset, 2344 prefix="OFFSET", 2345 dialect=dialect, 2346 copy=copy, 2347 **opts, 2348 ) 2349 2350 def select( 2351 self, 2352 *expressions: ExpOrStr, 2353 append: bool = True, 2354 dialect: DialectType = None, 2355 copy: bool = True, 2356 **opts, 2357 ) -> Select: 2358 """ 2359 Append to or set the SELECT expressions. 2360 2361 Example: 2362 >>> Select().select("x", "y").sql() 2363 'SELECT x, y' 2364 2365 Args: 2366 *expressions: the SQL code strings to parse. 2367 If an `Expression` instance is passed, it will be used as-is. 2368 append: if `True`, add to any existing expressions. 2369 Otherwise, this resets the expressions. 2370 dialect: the dialect used to parse the input expressions. 2371 copy: if `False`, modify this expression instance in-place. 2372 opts: other options to use to parse the input expressions. 2373 2374 Returns: 2375 Select: the modified expression. 2376 """ 2377 return _apply_list_builder( 2378 *expressions, 2379 instance=self, 2380 arg="expressions", 2381 append=append, 2382 dialect=dialect, 2383 copy=copy, 2384 **opts, 2385 ) 2386 2387 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2388 """ 2389 Append to or set the LATERAL expressions. 2390 2391 Example: 2392 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2393 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2394 2395 Args: 2396 *expressions (str | Expression): the SQL code strings to parse. 2397 If an `Expression` instance is passed, it will be used as-is. 2398 append (bool): if `True`, add to any existing expressions. 2399 Otherwise, this resets the expressions. 2400 dialect (str): the dialect used to parse the input expressions. 2401 copy (bool): if `False`, modify this expression instance in-place. 2402 opts (kwargs): other options to use to parse the input expressions. 2403 2404 Returns: 2405 Select: the modified expression. 2406 """ 2407 return _apply_list_builder( 2408 *expressions, 2409 instance=self, 2410 arg="laterals", 2411 append=append, 2412 into=Lateral, 2413 prefix="LATERAL VIEW", 2414 dialect=dialect, 2415 copy=copy, 2416 **opts, 2417 ) 2418 2419 def join( 2420 self, 2421 expression, 2422 on=None, 2423 using=None, 2424 append=True, 2425 join_type=None, 2426 join_alias=None, 2427 dialect=None, 2428 copy=True, 2429 **opts, 2430 ) -> Select: 2431 """ 2432 Append to or set the JOIN expressions. 2433 2434 Example: 2435 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2436 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2437 2438 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2439 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2440 2441 Use `join_type` to change the type of join: 2442 2443 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2444 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2445 2446 Args: 2447 expression (str | Expression): the SQL code string to parse. 2448 If an `Expression` instance is passed, it will be used as-is. 2449 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2450 If an `Expression` instance is passed, it will be used as-is. 2451 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2452 If an `Expression` instance is passed, it will be used as-is. 2453 append (bool): if `True`, add to any existing expressions. 2454 Otherwise, this resets the expressions. 2455 join_type (str): If set, alter the parsed join type 2456 dialect (str): the dialect used to parse the input expressions. 2457 copy (bool): if `False`, modify this expression instance in-place. 2458 opts (kwargs): other options to use to parse the input expressions. 2459 2460 Returns: 2461 Select: the modified expression. 2462 """ 2463 parse_args = {"dialect": dialect, **opts} 2464 2465 try: 2466 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2467 except ParseError: 2468 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2469 2470 join = expression if isinstance(expression, Join) else Join(this=expression) 2471 2472 if isinstance(join.this, Select): 2473 join.this.replace(join.this.subquery()) 2474 2475 if join_type: 2476 natural: t.Optional[Token] 2477 side: t.Optional[Token] 2478 kind: t.Optional[Token] 2479 2480 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2481 2482 if natural: 2483 join.set("natural", True) 2484 if side: 2485 join.set("side", side.text) 2486 if kind: 2487 join.set("kind", kind.text) 2488 2489 if on: 2490 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2491 join.set("on", on) 2492 2493 if using: 2494 join = _apply_list_builder( 2495 *ensure_collection(using), 2496 instance=join, 2497 arg="using", 2498 append=append, 2499 copy=copy, 2500 **opts, 2501 ) 2502 2503 if join_alias: 2504 join.set("this", alias_(join.this, join_alias, table=True)) 2505 return _apply_list_builder( 2506 join, 2507 instance=self, 2508 arg="joins", 2509 append=append, 2510 copy=copy, 2511 **opts, 2512 ) 2513 2514 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2515 """ 2516 Append to or set the WHERE expressions. 2517 2518 Example: 2519 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2520 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2521 2522 Args: 2523 *expressions (str | Expression): the SQL code strings to parse. 2524 If an `Expression` instance is passed, it will be used as-is. 2525 Multiple expressions are combined with an AND operator. 2526 append (bool): if `True`, AND the new expressions to any existing expression. 2527 Otherwise, this resets the expression. 2528 dialect (str): the dialect used to parse the input expressions. 2529 copy (bool): if `False`, modify this expression instance in-place. 2530 opts (kwargs): other options to use to parse the input expressions. 2531 2532 Returns: 2533 Select: the modified expression. 2534 """ 2535 return _apply_conjunction_builder( 2536 *expressions, 2537 instance=self, 2538 arg="where", 2539 append=append, 2540 into=Where, 2541 dialect=dialect, 2542 copy=copy, 2543 **opts, 2544 ) 2545 2546 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2547 """ 2548 Append to or set the HAVING expressions. 2549 2550 Example: 2551 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2552 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2553 2554 Args: 2555 *expressions (str | Expression): the SQL code strings to parse. 2556 If an `Expression` instance is passed, it will be used as-is. 2557 Multiple expressions are combined with an AND operator. 2558 append (bool): if `True`, AND the new expressions to any existing expression. 2559 Otherwise, this resets the expression. 2560 dialect (str): the dialect used to parse the input expressions. 2561 copy (bool): if `False`, modify this expression instance in-place. 2562 opts (kwargs): other options to use to parse the input expressions. 2563 2564 Returns: 2565 Select: the modified expression. 2566 """ 2567 return _apply_conjunction_builder( 2568 *expressions, 2569 instance=self, 2570 arg="having", 2571 append=append, 2572 into=Having, 2573 dialect=dialect, 2574 copy=copy, 2575 **opts, 2576 ) 2577 2578 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2579 return _apply_list_builder( 2580 *expressions, 2581 instance=self, 2582 arg="windows", 2583 append=append, 2584 into=Window, 2585 dialect=dialect, 2586 copy=copy, 2587 **opts, 2588 ) 2589 2590 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2591 return _apply_conjunction_builder( 2592 *expressions, 2593 instance=self, 2594 arg="qualify", 2595 append=append, 2596 into=Qualify, 2597 dialect=dialect, 2598 copy=copy, 2599 **opts, 2600 ) 2601 2602 def distinct(self, distinct=True, copy=True) -> Select: 2603 """ 2604 Set the OFFSET expression. 2605 2606 Example: 2607 >>> Select().from_("tbl").select("x").distinct().sql() 2608 'SELECT DISTINCT x FROM tbl' 2609 2610 Args: 2611 distinct (bool): whether the Select should be distinct 2612 copy (bool): if `False`, modify this expression instance in-place. 2613 2614 Returns: 2615 Select: the modified expression. 2616 """ 2617 instance = _maybe_copy(self, copy) 2618 instance.set("distinct", Distinct() if distinct else None) 2619 return instance 2620 2621 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2622 """ 2623 Convert this expression to a CREATE TABLE AS statement. 2624 2625 Example: 2626 >>> Select().select("*").from_("tbl").ctas("x").sql() 2627 'CREATE TABLE x AS SELECT * FROM tbl' 2628 2629 Args: 2630 table (str | Expression): the SQL code string to parse as the table name. 2631 If another `Expression` instance is passed, it will be used as-is. 2632 properties (dict): an optional mapping of table properties 2633 dialect (str): the dialect used to parse the input table. 2634 copy (bool): if `False`, modify this expression instance in-place. 2635 opts (kwargs): other options to use to parse the input table. 2636 2637 Returns: 2638 Create: the CREATE TABLE AS expression 2639 """ 2640 instance = _maybe_copy(self, copy) 2641 table_expression = maybe_parse( 2642 table, 2643 into=Table, 2644 dialect=dialect, 2645 **opts, 2646 ) 2647 properties_expression = None 2648 if properties: 2649 properties_expression = Properties.from_dict(properties) 2650 2651 return Create( 2652 this=table_expression, 2653 kind="table", 2654 expression=instance, 2655 properties=properties_expression, 2656 ) 2657 2658 def lock(self, update: bool = True, copy: bool = True) -> Select: 2659 """ 2660 Set the locking read mode for this expression. 2661 2662 Examples: 2663 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2664 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2665 2666 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2667 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2668 2669 Args: 2670 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2671 copy: if `False`, modify this expression instance in-place. 2672 2673 Returns: 2674 The modified expression. 2675 """ 2676 2677 inst = _maybe_copy(self, copy) 2678 inst.set("lock", Lock(update=update)) 2679 2680 return inst 2681 2682 @property 2683 def named_selects(self) -> t.List[str]: 2684 return [e.output_name for e in self.expressions if e.alias_or_name] 2685 2686 @property 2687 def is_star(self) -> bool: 2688 return any(expression.is_star for expression in self.expressions) 2689 2690 @property 2691 def selects(self) -> t.List[Expression]: 2692 return self.expressions 2693 2694 2695class Subquery(DerivedTable, Unionable): 2696 arg_types = { 2697 "this": True, 2698 "alias": False, 2699 "with": False, 2700 **QUERY_MODIFIERS, 2701 } 2702 2703 def unnest(self): 2704 """ 2705 Returns the first non subquery. 2706 """ 2707 expression = self 2708 while isinstance(expression, Subquery): 2709 expression = expression.this 2710 return expression 2711 2712 @property 2713 def is_star(self) -> bool: 2714 return self.this.is_star 2715 2716 @property 2717 def output_name(self): 2718 return self.alias 2719 2720 2721class TableSample(Expression): 2722 arg_types = { 2723 "this": False, 2724 "method": False, 2725 "bucket_numerator": False, 2726 "bucket_denominator": False, 2727 "bucket_field": False, 2728 "percent": False, 2729 "rows": False, 2730 "size": False, 2731 "seed": False, 2732 "kind": False, 2733 } 2734 2735 2736class Tag(Expression): 2737 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2738 2739 arg_types = { 2740 "this": False, 2741 "prefix": False, 2742 "postfix": False, 2743 } 2744 2745 2746class Pivot(Expression): 2747 arg_types = { 2748 "this": False, 2749 "alias": False, 2750 "expressions": True, 2751 "field": True, 2752 "unpivot": True, 2753 "columns": False, 2754 } 2755 2756 2757class Window(Expression): 2758 arg_types = { 2759 "this": True, 2760 "partition_by": False, 2761 "order": False, 2762 "spec": False, 2763 "alias": False, 2764 } 2765 2766 2767class WindowSpec(Expression): 2768 arg_types = { 2769 "kind": False, 2770 "start": False, 2771 "start_side": False, 2772 "end": False, 2773 "end_side": False, 2774 } 2775 2776 2777class Where(Expression): 2778 pass 2779 2780 2781class Star(Expression): 2782 arg_types = {"except": False, "replace": False} 2783 2784 @property 2785 def name(self) -> str: 2786 return "*" 2787 2788 @property 2789 def output_name(self): 2790 return self.name 2791 2792 2793class Parameter(Expression): 2794 arg_types = {"this": True, "wrapped": False} 2795 2796 2797class SessionParameter(Expression): 2798 arg_types = {"this": True, "kind": False} 2799 2800 2801class Placeholder(Expression): 2802 arg_types = {"this": False} 2803 2804 2805class Null(Condition): 2806 arg_types: t.Dict[str, t.Any] = {} 2807 2808 @property 2809 def name(self) -> str: 2810 return "NULL" 2811 2812 2813class Boolean(Condition): 2814 pass 2815 2816 2817class DataType(Expression): 2818 arg_types = { 2819 "this": True, 2820 "expressions": False, 2821 "nested": False, 2822 "values": False, 2823 "prefix": False, 2824 } 2825 2826 class Type(AutoName): 2827 CHAR = auto() 2828 NCHAR = auto() 2829 VARCHAR = auto() 2830 NVARCHAR = auto() 2831 TEXT = auto() 2832 MEDIUMTEXT = auto() 2833 LONGTEXT = auto() 2834 MEDIUMBLOB = auto() 2835 LONGBLOB = auto() 2836 BINARY = auto() 2837 VARBINARY = auto() 2838 INT = auto() 2839 UINT = auto() 2840 TINYINT = auto() 2841 UTINYINT = auto() 2842 SMALLINT = auto() 2843 USMALLINT = auto() 2844 BIGINT = auto() 2845 UBIGINT = auto() 2846 FLOAT = auto() 2847 DOUBLE = auto() 2848 DECIMAL = auto() 2849 BIGDECIMAL = auto() 2850 BIT = auto() 2851 BOOLEAN = auto() 2852 JSON = auto() 2853 JSONB = auto() 2854 INTERVAL = auto() 2855 TIME = auto() 2856 TIMESTAMP = auto() 2857 TIMESTAMPTZ = auto() 2858 TIMESTAMPLTZ = auto() 2859 DATE = auto() 2860 DATETIME = auto() 2861 ARRAY = auto() 2862 MAP = auto() 2863 UUID = auto() 2864 GEOGRAPHY = auto() 2865 GEOMETRY = auto() 2866 STRUCT = auto() 2867 NULLABLE = auto() 2868 HLLSKETCH = auto() 2869 HSTORE = auto() 2870 SUPER = auto() 2871 SERIAL = auto() 2872 SMALLSERIAL = auto() 2873 BIGSERIAL = auto() 2874 XML = auto() 2875 UNIQUEIDENTIFIER = auto() 2876 MONEY = auto() 2877 SMALLMONEY = auto() 2878 ROWVERSION = auto() 2879 IMAGE = auto() 2880 VARIANT = auto() 2881 OBJECT = auto() 2882 INET = auto() 2883 NULL = auto() 2884 UNKNOWN = auto() # Sentinel value, useful for type annotation 2885 2886 TEXT_TYPES = { 2887 Type.CHAR, 2888 Type.NCHAR, 2889 Type.VARCHAR, 2890 Type.NVARCHAR, 2891 Type.TEXT, 2892 } 2893 2894 INTEGER_TYPES = { 2895 Type.INT, 2896 Type.TINYINT, 2897 Type.SMALLINT, 2898 Type.BIGINT, 2899 } 2900 2901 FLOAT_TYPES = { 2902 Type.FLOAT, 2903 Type.DOUBLE, 2904 } 2905 2906 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2907 2908 TEMPORAL_TYPES = { 2909 Type.TIMESTAMP, 2910 Type.TIMESTAMPTZ, 2911 Type.TIMESTAMPLTZ, 2912 Type.DATE, 2913 Type.DATETIME, 2914 } 2915 2916 @classmethod 2917 def build( 2918 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2919 ) -> DataType: 2920 from sqlglot import parse_one 2921 2922 if isinstance(dtype, str): 2923 if dtype.upper() in cls.Type.__members__: 2924 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2925 else: 2926 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2927 if data_type_exp is None: 2928 raise ValueError(f"Unparsable data type value: {dtype}") 2929 elif isinstance(dtype, DataType.Type): 2930 data_type_exp = DataType(this=dtype) 2931 elif isinstance(dtype, DataType): 2932 return dtype 2933 else: 2934 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2935 return DataType(**{**data_type_exp.args, **kwargs}) 2936 2937 def is_type(self, dtype: DataType.Type) -> bool: 2938 return self.this == dtype 2939 2940 2941# https://www.postgresql.org/docs/15/datatype-pseudo.html 2942class PseudoType(Expression): 2943 pass 2944 2945 2946class StructKwarg(Expression): 2947 arg_types = {"this": True, "expression": True} 2948 2949 2950# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...) 2951class SubqueryPredicate(Predicate): 2952 pass 2953 2954 2955class All(SubqueryPredicate): 2956 pass 2957 2958 2959class Any(SubqueryPredicate): 2960 pass 2961 2962 2963class Exists(SubqueryPredicate): 2964 pass 2965 2966 2967# Commands to interact with the databases or engines. For most of the command 2968# expressions we parse whatever comes after the command's name as a string. 2969class Command(Expression): 2970 arg_types = {"this": True, "expression": False} 2971 2972 2973class Transaction(Expression): 2974 arg_types = {"this": False, "modes": False} 2975 2976 2977class Commit(Expression): 2978 arg_types = {"chain": False} 2979 2980 2981class Rollback(Expression): 2982 arg_types = {"savepoint": False} 2983 2984 2985class AlterTable(Expression): 2986 arg_types = {"this": True, "actions": True, "exists": False} 2987 2988 2989class AddConstraint(Expression): 2990 arg_types = {"this": False, "expression": False, "enforced": False} 2991 2992 2993class DropPartition(Expression): 2994 arg_types = {"expressions": True, "exists": False} 2995 2996 2997# Binary expressions like (ADD a b) 2998class Binary(Expression): 2999 arg_types = {"this": True, "expression": True} 3000 3001 @property 3002 def left(self): 3003 return self.this 3004 3005 @property 3006 def right(self): 3007 return self.expression 3008 3009 3010class Add(Binary): 3011 pass 3012 3013 3014class Connector(Binary, Condition): 3015 pass 3016 3017 3018class And(Connector): 3019 pass 3020 3021 3022class Or(Connector): 3023 pass 3024 3025 3026class BitwiseAnd(Binary): 3027 pass 3028 3029 3030class BitwiseLeftShift(Binary): 3031 pass 3032 3033 3034class BitwiseOr(Binary): 3035 pass 3036 3037 3038class BitwiseRightShift(Binary): 3039 pass 3040 3041 3042class BitwiseXor(Binary): 3043 pass 3044 3045 3046class Div(Binary): 3047 pass 3048 3049 3050class Overlaps(Binary): 3051 pass 3052 3053 3054class Dot(Binary): 3055 @property 3056 def name(self) -> str: 3057 return self.expression.name 3058 3059 @classmethod 3060 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3061 """Build a Dot object with a sequence of expressions.""" 3062 if len(expressions) < 2: 3063 raise ValueError(f"Dot requires >= 2 expressions.") 3064 3065 a, b, *expressions = expressions 3066 dot = Dot(this=a, expression=b) 3067 3068 for expression in expressions: 3069 dot = Dot(this=dot, expression=expression) 3070 3071 return dot 3072 3073 3074class DPipe(Binary): 3075 pass 3076 3077 3078class EQ(Binary, Predicate): 3079 pass 3080 3081 3082class NullSafeEQ(Binary, Predicate): 3083 pass 3084 3085 3086class NullSafeNEQ(Binary, Predicate): 3087 pass 3088 3089 3090class Distance(Binary): 3091 pass 3092 3093 3094class Escape(Binary): 3095 pass 3096 3097 3098class Glob(Binary, Predicate): 3099 pass 3100 3101 3102class GT(Binary, Predicate): 3103 pass 3104 3105 3106class GTE(Binary, Predicate): 3107 pass 3108 3109 3110class ILike(Binary, Predicate): 3111 pass 3112 3113 3114class ILikeAny(Binary, Predicate): 3115 pass 3116 3117 3118class IntDiv(Binary): 3119 pass 3120 3121 3122class Is(Binary, Predicate): 3123 pass 3124 3125 3126class Kwarg(Binary): 3127 """Kwarg in special functions like func(kwarg => y).""" 3128 3129 3130class Like(Binary, Predicate): 3131 pass 3132 3133 3134class LikeAny(Binary, Predicate): 3135 pass 3136 3137 3138class LT(Binary, Predicate): 3139 pass 3140 3141 3142class LTE(Binary, Predicate): 3143 pass 3144 3145 3146class Mod(Binary): 3147 pass 3148 3149 3150class Mul(Binary): 3151 pass 3152 3153 3154class NEQ(Binary, Predicate): 3155 pass 3156 3157 3158class SimilarTo(Binary, Predicate): 3159 pass 3160 3161 3162class Slice(Binary): 3163 arg_types = {"this": False, "expression": False} 3164 3165 3166class Sub(Binary): 3167 pass 3168 3169 3170class ArrayOverlaps(Binary): 3171 pass 3172 3173 3174# Unary Expressions 3175# (NOT a) 3176class Unary(Expression): 3177 pass 3178 3179 3180class BitwiseNot(Unary): 3181 pass 3182 3183 3184class Not(Unary, Condition): 3185 pass 3186 3187 3188class Paren(Unary, Condition): 3189 arg_types = {"this": True, "with": False} 3190 3191 3192class Neg(Unary): 3193 pass 3194 3195 3196class Alias(Expression): 3197 arg_types = {"this": True, "alias": False} 3198 3199 @property 3200 def output_name(self): 3201 return self.alias 3202 3203 3204class Aliases(Expression): 3205 arg_types = {"this": True, "expressions": True} 3206 3207 @property 3208 def aliases(self): 3209 return self.expressions 3210 3211 3212class AtTimeZone(Expression): 3213 arg_types = {"this": True, "zone": True} 3214 3215 3216class Between(Predicate): 3217 arg_types = {"this": True, "low": True, "high": True} 3218 3219 3220class Bracket(Condition): 3221 arg_types = {"this": True, "expressions": True} 3222 3223 3224class Distinct(Expression): 3225 arg_types = {"expressions": False, "on": False} 3226 3227 3228class In(Predicate): 3229 arg_types = { 3230 "this": True, 3231 "expressions": False, 3232 "query": False, 3233 "unnest": False, 3234 "field": False, 3235 "is_global": False, 3236 } 3237 3238 3239class TimeUnit(Expression): 3240 """Automatically converts unit arg into a var.""" 3241 3242 arg_types = {"unit": False} 3243 3244 def __init__(self, **args): 3245 unit = args.get("unit") 3246 if isinstance(unit, (Column, Literal)): 3247 args["unit"] = Var(this=unit.name) 3248 elif isinstance(unit, Week): 3249 unit.set("this", Var(this=unit.this.name)) 3250 super().__init__(**args) 3251 3252 3253class Interval(TimeUnit): 3254 arg_types = {"this": False, "unit": False} 3255 3256 3257class IgnoreNulls(Expression): 3258 pass 3259 3260 3261class RespectNulls(Expression): 3262 pass 3263 3264 3265# Functions 3266class Func(Condition): 3267 """ 3268 The base class for all function expressions. 3269 3270 Attributes: 3271 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3272 treated as a variable length argument and the argument's value will be stored as a list. 3273 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3274 for this function expression. These values are used to map this node to a name during parsing 3275 as well as to provide the function's name during SQL string generation. By default the SQL 3276 name is set to the expression's class name transformed to snake case. 3277 """ 3278 3279 is_var_len_args = False 3280 3281 @classmethod 3282 def from_arg_list(cls, args): 3283 if cls.is_var_len_args: 3284 all_arg_keys = list(cls.arg_types) 3285 # If this function supports variable length argument treat the last argument as such. 3286 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3287 num_non_var = len(non_var_len_arg_keys) 3288 3289 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3290 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3291 else: 3292 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3293 3294 return cls(**args_dict) 3295 3296 @classmethod 3297 def sql_names(cls): 3298 if cls is Func: 3299 raise NotImplementedError( 3300 "SQL name is only supported by concrete function implementations" 3301 ) 3302 if "_sql_names" not in cls.__dict__: 3303 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3304 return cls._sql_names 3305 3306 @classmethod 3307 def sql_name(cls): 3308 return cls.sql_names()[0] 3309 3310 @classmethod 3311 def default_parser_mappings(cls): 3312 return {name: cls.from_arg_list for name in cls.sql_names()} 3313 3314 3315class AggFunc(Func): 3316 pass 3317 3318 3319class Abs(Func): 3320 pass 3321 3322 3323class Anonymous(Func): 3324 arg_types = {"this": True, "expressions": False} 3325 is_var_len_args = True 3326 3327 3328# https://docs.snowflake.com/en/sql-reference/functions/hll 3329# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html 3330class Hll(AggFunc): 3331 arg_types = {"this": True, "expressions": False} 3332 is_var_len_args = True 3333 3334 3335class ApproxDistinct(AggFunc): 3336 arg_types = {"this": True, "accuracy": False} 3337 3338 3339class Array(Func): 3340 arg_types = {"expressions": False} 3341 is_var_len_args = True 3342 3343 3344# https://docs.snowflake.com/en/sql-reference/functions/to_char 3345class ToChar(Func): 3346 arg_types = {"this": True, "format": False} 3347 3348 3349class GenerateSeries(Func): 3350 arg_types = {"start": True, "end": True, "step": False} 3351 3352 3353class ArrayAgg(AggFunc): 3354 pass 3355 3356 3357class ArrayAll(Func): 3358 arg_types = {"this": True, "expression": True} 3359 3360 3361class ArrayAny(Func): 3362 arg_types = {"this": True, "expression": True} 3363 3364 3365class ArrayConcat(Func): 3366 arg_types = {"this": True, "expressions": False} 3367 is_var_len_args = True 3368 3369 3370class ArrayContains(Binary, Func): 3371 pass 3372 3373 3374class ArrayContained(Binary): 3375 pass 3376 3377 3378class ArrayFilter(Func): 3379 arg_types = {"this": True, "expression": True} 3380 _sql_names = ["FILTER", "ARRAY_FILTER"] 3381 3382 3383class ArrayJoin(Func): 3384 arg_types = {"this": True, "expression": True, "null": False} 3385 3386 3387class ArraySize(Func): 3388 arg_types = {"this": True, "expression": False} 3389 3390 3391class ArraySort(Func): 3392 arg_types = {"this": True, "expression": False} 3393 3394 3395class ArraySum(Func): 3396 pass 3397 3398 3399class ArrayUnionAgg(AggFunc): 3400 pass 3401 3402 3403class Avg(AggFunc): 3404 pass 3405 3406 3407class AnyValue(AggFunc): 3408 pass 3409 3410 3411class Case(Func): 3412 arg_types = {"this": False, "ifs": True, "default": False} 3413 3414 3415class Cast(Func): 3416 arg_types = {"this": True, "to": True} 3417 3418 @property 3419 def name(self) -> str: 3420 return self.this.name 3421 3422 @property 3423 def to(self): 3424 return self.args["to"] 3425 3426 @property 3427 def output_name(self): 3428 return self.name 3429 3430 def is_type(self, dtype: DataType.Type) -> bool: 3431 return self.to.is_type(dtype) 3432 3433 3434class Collate(Binary): 3435 pass 3436 3437 3438class TryCast(Cast): 3439 pass 3440 3441 3442class Ceil(Func): 3443 arg_types = {"this": True, "decimals": False} 3444 _sql_names = ["CEIL", "CEILING"] 3445 3446 3447class Coalesce(Func): 3448 arg_types = {"this": True, "expressions": False} 3449 is_var_len_args = True 3450 3451 3452class Concat(Func): 3453 arg_types = {"expressions": True} 3454 is_var_len_args = True 3455 3456 3457class ConcatWs(Concat): 3458 _sql_names = ["CONCAT_WS"] 3459 3460 3461class Count(AggFunc): 3462 arg_types = {"this": False} 3463 3464 3465class CountIf(AggFunc): 3466 pass 3467 3468 3469class CurrentDate(Func): 3470 arg_types = {"this": False} 3471 3472 3473class CurrentDatetime(Func): 3474 arg_types = {"this": False} 3475 3476 3477class CurrentTime(Func): 3478 arg_types = {"this": False} 3479 3480 3481class CurrentTimestamp(Func): 3482 arg_types = {"this": False} 3483 3484 3485class CurrentUser(Func): 3486 arg_types = {"this": False} 3487 3488 3489class DateAdd(Func, TimeUnit): 3490 arg_types = {"this": True, "expression": True, "unit": False} 3491 3492 3493class DateSub(Func, TimeUnit): 3494 arg_types = {"this": True, "expression": True, "unit": False} 3495 3496 3497class DateDiff(Func, TimeUnit): 3498 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3499 arg_types = {"this": True, "expression": True, "unit": False} 3500 3501 3502class DateTrunc(Func): 3503 arg_types = {"unit": True, "this": True, "zone": False} 3504 3505 3506class DatetimeAdd(Func, TimeUnit): 3507 arg_types = {"this": True, "expression": True, "unit": False} 3508 3509 3510class DatetimeSub(Func, TimeUnit): 3511 arg_types = {"this": True, "expression": True, "unit": False} 3512 3513 3514class DatetimeDiff(Func, TimeUnit): 3515 arg_types = {"this": True, "expression": True, "unit": False} 3516 3517 3518class DatetimeTrunc(Func, TimeUnit): 3519 arg_types = {"this": True, "unit": True, "zone": False} 3520 3521 3522class DayOfWeek(Func): 3523 _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"] 3524 3525 3526class DayOfMonth(Func): 3527 _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"] 3528 3529 3530class DayOfYear(Func): 3531 _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"] 3532 3533 3534class WeekOfYear(Func): 3535 _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"] 3536 3537 3538class LastDateOfMonth(Func): 3539 pass 3540 3541 3542class Extract(Func): 3543 arg_types = {"this": True, "expression": True} 3544 3545 3546class TimestampAdd(Func, TimeUnit): 3547 arg_types = {"this": True, "expression": True, "unit": False} 3548 3549 3550class TimestampSub(Func, TimeUnit): 3551 arg_types = {"this": True, "expression": True, "unit": False} 3552 3553 3554class TimestampDiff(Func, TimeUnit): 3555 arg_types = {"this": True, "expression": True, "unit": False} 3556 3557 3558class TimestampTrunc(Func, TimeUnit): 3559 arg_types = {"this": True, "unit": True, "zone": False} 3560 3561 3562class TimeAdd(Func, TimeUnit): 3563 arg_types = {"this": True, "expression": True, "unit": False} 3564 3565 3566class TimeSub(Func, TimeUnit): 3567 arg_types = {"this": True, "expression": True, "unit": False} 3568 3569 3570class TimeDiff(Func, TimeUnit): 3571 arg_types = {"this": True, "expression": True, "unit": False} 3572 3573 3574class TimeTrunc(Func, TimeUnit): 3575 arg_types = {"this": True, "unit": True, "zone": False} 3576 3577 3578class DateFromParts(Func): 3579 _sql_names = ["DATEFROMPARTS"] 3580 arg_types = {"year": True, "month": True, "day": True} 3581 3582 3583class DateStrToDate(Func): 3584 pass 3585 3586 3587class DateToDateStr(Func): 3588 pass 3589 3590 3591class DateToDi(Func): 3592 pass 3593 3594 3595class Day(Func): 3596 pass 3597 3598 3599class Decode(Func): 3600 arg_types = {"this": True, "charset": True, "replace": False} 3601 3602 3603class DiToDate(Func): 3604 pass 3605 3606 3607class Encode(Func): 3608 arg_types = {"this": True, "charset": True} 3609 3610 3611class Exp(Func): 3612 pass 3613 3614 3615class Explode(Func): 3616 pass 3617 3618 3619class ExponentialTimeDecayedAvg(AggFunc): 3620 arg_types = {"this": True, "time": False, "decay": False} 3621 3622 3623class Floor(Func): 3624 arg_types = {"this": True, "decimals": False} 3625 3626 3627class Greatest(Func): 3628 arg_types = {"this": True, "expressions": False} 3629 is_var_len_args = True 3630 3631 3632class GroupConcat(Func): 3633 arg_types = {"this": True, "separator": False} 3634 3635 3636class GroupUniqArray(AggFunc): 3637 arg_types = {"this": True, "size": False} 3638 3639 3640class Hex(Func): 3641 pass 3642 3643 3644class Histogram(AggFunc): 3645 arg_types = {"this": True, "bins": False} 3646 3647 3648class If(Func): 3649 arg_types = {"this": True, "true": True, "false": False} 3650 3651 3652class IfNull(Func): 3653 arg_types = {"this": True, "expression": False} 3654 _sql_names = ["IFNULL", "NVL"] 3655 3656 3657class Initcap(Func): 3658 pass 3659 3660 3661class JSONKeyValue(Expression): 3662 arg_types = {"this": True, "expression": True} 3663 3664 3665class JSONObject(Func): 3666 arg_types = { 3667 "expressions": False, 3668 "null_handling": False, 3669 "unique_keys": False, 3670 "return_type": False, 3671 "format_json": False, 3672 "encoding": False, 3673 } 3674 3675 3676class JSONBContains(Binary): 3677 _sql_names = ["JSONB_CONTAINS"] 3678 3679 3680class JSONExtract(Binary, Func): 3681 _sql_names = ["JSON_EXTRACT"] 3682 3683 3684class JSONExtractScalar(JSONExtract): 3685 _sql_names = ["JSON_EXTRACT_SCALAR"] 3686 3687 3688class JSONBExtract(JSONExtract): 3689 _sql_names = ["JSONB_EXTRACT"] 3690 3691 3692class JSONBExtractScalar(JSONExtract): 3693 _sql_names = ["JSONB_EXTRACT_SCALAR"] 3694 3695 3696class JSONFormat(Func): 3697 arg_types = {"this": False, "options": False} 3698 _sql_names = ["JSON_FORMAT"] 3699 3700 3701class Least(Func): 3702 arg_types = {"expressions": False} 3703 is_var_len_args = True 3704 3705 3706class Length(Func): 3707 pass 3708 3709 3710class Levenshtein(Func): 3711 arg_types = { 3712 "this": True, 3713 "expression": False, 3714 "ins_cost": False, 3715 "del_cost": False, 3716 "sub_cost": False, 3717 } 3718 3719 3720class Ln(Func): 3721 pass 3722 3723 3724class Log(Func): 3725 arg_types = {"this": True, "expression": False} 3726 3727 3728class Log2(Func): 3729 pass 3730 3731 3732class Log10(Func): 3733 pass 3734 3735 3736class LogicalOr(AggFunc): 3737 _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"] 3738 3739 3740class LogicalAnd(AggFunc): 3741 _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"] 3742 3743 3744class Lower(Func): 3745 _sql_names = ["LOWER", "LCASE"] 3746 3747 3748class Map(Func): 3749 arg_types = {"keys": False, "values": False} 3750 3751 3752class VarMap(Func): 3753 arg_types = {"keys": True, "values": True} 3754 is_var_len_args = True 3755 3756 3757# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html 3758class MatchAgainst(Func): 3759 arg_types = {"this": True, "expressions": True, "modifier": False} 3760 3761 3762class Max(AggFunc): 3763 arg_types = {"this": True, "expressions": False} 3764 is_var_len_args = True 3765 3766 3767class Min(AggFunc): 3768 arg_types = {"this": True, "expressions": False} 3769 is_var_len_args = True 3770 3771 3772class Month(Func): 3773 pass 3774 3775 3776class Nvl2(Func): 3777 arg_types = {"this": True, "true": True, "false": False} 3778 3779 3780class Posexplode(Func): 3781 pass 3782 3783 3784class Pow(Binary, Func): 3785 _sql_names = ["POWER", "POW"] 3786 3787 3788class PercentileCont(AggFunc): 3789 pass 3790 3791 3792class PercentileDisc(AggFunc): 3793 pass 3794 3795 3796class Quantile(AggFunc): 3797 arg_types = {"this": True, "quantile": True} 3798 3799 3800# Clickhouse-specific: 3801# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles 3802class Quantiles(AggFunc): 3803 arg_types = {"parameters": True, "expressions": True} 3804 is_var_len_args = True 3805 3806 3807class QuantileIf(AggFunc): 3808 arg_types = {"parameters": True, "expressions": True} 3809 3810 3811class ApproxQuantile(Quantile): 3812 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False} 3813 3814 3815class RangeN(Func): 3816 arg_types = {"this": True, "expressions": True, "each": False} 3817 3818 3819class ReadCSV(Func): 3820 _sql_names = ["READ_CSV"] 3821 is_var_len_args = True 3822 arg_types = {"this": True, "expressions": False} 3823 3824 3825class Reduce(Func): 3826 arg_types = {"this": True, "initial": True, "merge": True, "finish": False} 3827 3828 3829class RegexpExtract(Func): 3830 arg_types = { 3831 "this": True, 3832 "expression": True, 3833 "position": False, 3834 "occurrence": False, 3835 "group": False, 3836 } 3837 3838 3839class RegexpLike(Func): 3840 arg_types = {"this": True, "expression": True, "flag": False} 3841 3842 3843class RegexpILike(Func): 3844 arg_types = {"this": True, "expression": True, "flag": False} 3845 3846 3847# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html 3848# limit is the number of times a pattern is applied 3849class RegexpSplit(Func): 3850 arg_types = {"this": True, "expression": True, "limit": False} 3851 3852 3853class Repeat(Func): 3854 arg_types = {"this": True, "times": True} 3855 3856 3857class Round(Func): 3858 arg_types = {"this": True, "decimals": False} 3859 3860 3861class RowNumber(Func): 3862 arg_types: t.Dict[str, t.Any] = {} 3863 3864 3865class SafeDivide(Func): 3866 arg_types = {"this": True, "expression": True} 3867 3868 3869class SetAgg(AggFunc): 3870 pass 3871 3872 3873class SortArray(Func): 3874 arg_types = {"this": True, "asc": False} 3875 3876 3877class Split(Func): 3878 arg_types = {"this": True, "expression": True, "limit": False} 3879 3880 3881# Start may be omitted in the case of postgres 3882# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6 3883class Substring(Func): 3884 arg_types = {"this": True, "start": False, "length": False} 3885 3886 3887class StrPosition(Func): 3888 arg_types = { 3889 "this": True, 3890 "substr": True, 3891 "position": False, 3892 "instance": False, 3893 } 3894 3895 3896class StrToDate(Func): 3897 arg_types = {"this": True, "format": True} 3898 3899 3900class StrToTime(Func): 3901 arg_types = {"this": True, "format": True} 3902 3903 3904# Spark allows unix_timestamp() 3905# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html 3906class StrToUnix(Func): 3907 arg_types = {"this": False, "format": False} 3908 3909 3910class NumberToStr(Func): 3911 arg_types = {"this": True, "format": True} 3912 3913 3914class Struct(Func): 3915 arg_types = {"expressions": True} 3916 is_var_len_args = True 3917 3918 3919class StructExtract(Func): 3920 arg_types = {"this": True, "expression": True} 3921 3922 3923class Sum(AggFunc): 3924 pass 3925 3926 3927class Sqrt(Func): 3928 pass 3929 3930 3931class Stddev(AggFunc): 3932 pass 3933 3934 3935class StddevPop(AggFunc): 3936 pass 3937 3938 3939class StddevSamp(AggFunc): 3940 pass 3941 3942 3943class TimeToStr(Func): 3944 arg_types = {"this": True, "format": True} 3945 3946 3947class TimeToTimeStr(Func): 3948 pass 3949 3950 3951class TimeToUnix(Func): 3952 pass 3953 3954 3955class TimeStrToDate(Func): 3956 pass 3957 3958 3959class TimeStrToTime(Func): 3960 pass 3961 3962 3963class TimeStrToUnix(Func): 3964 pass 3965 3966 3967class Trim(Func): 3968 arg_types = { 3969 "this": True, 3970 "expression": False, 3971 "position": False, 3972 "collation": False, 3973 } 3974 3975 3976class TsOrDsAdd(Func, TimeUnit): 3977 arg_types = {"this": True, "expression": True, "unit": False} 3978 3979 3980class TsOrDsToDateStr(Func): 3981 pass 3982 3983 3984class TsOrDsToDate(Func): 3985 arg_types = {"this": True, "format": False} 3986 3987 3988class TsOrDiToDi(Func): 3989 pass 3990 3991 3992class Unhex(Func): 3993 pass 3994 3995 3996class UnixToStr(Func): 3997 arg_types = {"this": True, "format": False} 3998 3999 4000# https://prestodb.io/docs/current/functions/datetime.html 4001# presto has weird zone/hours/minutes 4002class UnixToTime(Func): 4003 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4004 4005 SECONDS = Literal.string("seconds") 4006 MILLIS = Literal.string("millis") 4007 MICROS = Literal.string("micros") 4008 4009 4010class UnixToTimeStr(Func): 4011 pass 4012 4013 4014class Upper(Func): 4015 _sql_names = ["UPPER", "UCASE"] 4016 4017 4018class Variance(AggFunc): 4019 _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"] 4020 4021 4022class VariancePop(AggFunc): 4023 _sql_names = ["VARIANCE_POP", "VAR_POP"] 4024 4025 4026class Week(Func): 4027 arg_types = {"this": True, "mode": False} 4028 4029 4030class XMLTable(Func): 4031 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False} 4032 4033 4034class Year(Func): 4035 pass 4036 4037 4038class Use(Expression): 4039 arg_types = {"this": True, "kind": False} 4040 4041 4042class Merge(Expression): 4043 arg_types = {"this": True, "using": True, "on": True, "expressions": True} 4044 4045 4046class When(Func): 4047 arg_types = {"matched": True, "source": False, "condition": False, "then": True} 4048 4049 4050def _norm_arg(arg): 4051 return arg.lower() if type(arg) is str else arg 4052 4053 4054ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func)) 4055 4056 4057# Helpers 4058@t.overload 4059def maybe_parse( 4060 sql_or_expression: ExpOrStr, 4061 *, 4062 into: t.Type[E], 4063 dialect: DialectType = None, 4064 prefix: t.Optional[str] = None, 4065 copy: bool = False, 4066 **opts, 4067) -> E: 4068 ... 4069 4070 4071@t.overload 4072def maybe_parse( 4073 sql_or_expression: str | E, 4074 *, 4075 into: t.Optional[IntoType] = None, 4076 dialect: DialectType = None, 4077 prefix: t.Optional[str] = None, 4078 copy: bool = False, 4079 **opts, 4080) -> E: 4081 ... 4082 4083 4084def maybe_parse( 4085 sql_or_expression: ExpOrStr, 4086 *, 4087 into: t.Optional[IntoType] = None, 4088 dialect: DialectType = None, 4089 prefix: t.Optional[str] = None, 4090 copy: bool = False, 4091 **opts, 4092) -> Expression: 4093 """Gracefully handle a possible string or expression. 4094 4095 Example: 4096 >>> maybe_parse("1") 4097 (LITERAL this: 1, is_string: False) 4098 >>> maybe_parse(to_identifier("x")) 4099 (IDENTIFIER this: x, quoted: False) 4100 4101 Args: 4102 sql_or_expression: the SQL code string or an expression 4103 into: the SQLGlot Expression to parse into 4104 dialect: the dialect used to parse the input expressions (in the case that an 4105 input expression is a SQL string). 4106 prefix: a string to prefix the sql with before it gets parsed 4107 (automatically includes a space) 4108 copy: whether or not to copy the expression. 4109 **opts: other options to use to parse the input expressions (again, in the case 4110 that an input expression is a SQL string). 4111 4112 Returns: 4113 Expression: the parsed or given expression. 4114 """ 4115 if isinstance(sql_or_expression, Expression): 4116 if copy: 4117 return sql_or_expression.copy() 4118 return sql_or_expression 4119 4120 import sqlglot 4121 4122 sql = str(sql_or_expression) 4123 if prefix: 4124 sql = f"{prefix} {sql}" 4125 return sqlglot.parse_one(sql, read=dialect, into=into, **opts) 4126 4127 4128def _maybe_copy(instance, copy=True): 4129 return instance.copy() if copy else instance 4130 4131 4132def _is_wrong_expression(expression, into): 4133 return isinstance(expression, Expression) and not isinstance(expression, into) 4134 4135 4136def _apply_builder( 4137 expression, 4138 instance, 4139 arg, 4140 copy=True, 4141 prefix=None, 4142 into=None, 4143 dialect=None, 4144 **opts, 4145): 4146 if _is_wrong_expression(expression, into): 4147 expression = into(this=expression) 4148 instance = _maybe_copy(instance, copy) 4149 expression = maybe_parse( 4150 sql_or_expression=expression, 4151 prefix=prefix, 4152 into=into, 4153 dialect=dialect, 4154 **opts, 4155 ) 4156 instance.set(arg, expression) 4157 return instance 4158 4159 4160def _apply_child_list_builder( 4161 *expressions, 4162 instance, 4163 arg, 4164 append=True, 4165 copy=True, 4166 prefix=None, 4167 into=None, 4168 dialect=None, 4169 properties=None, 4170 **opts, 4171): 4172 instance = _maybe_copy(instance, copy) 4173 parsed = [] 4174 for expression in expressions: 4175 if _is_wrong_expression(expression, into): 4176 expression = into(expressions=[expression]) 4177 expression = maybe_parse( 4178 expression, 4179 into=into, 4180 dialect=dialect, 4181 prefix=prefix, 4182 **opts, 4183 ) 4184 parsed.extend(expression.expressions) 4185 4186 existing = instance.args.get(arg) 4187 if append and existing: 4188 parsed = existing.expressions + parsed 4189 4190 child = into(expressions=parsed) 4191 for k, v in (properties or {}).items(): 4192 child.set(k, v) 4193 instance.set(arg, child) 4194 return instance 4195 4196 4197def _apply_list_builder( 4198 *expressions, 4199 instance, 4200 arg, 4201 append=True, 4202 copy=True, 4203 prefix=None, 4204 into=None, 4205 dialect=None, 4206 **opts, 4207): 4208 inst = _maybe_copy(instance, copy) 4209 4210 expressions = [ 4211 maybe_parse( 4212 sql_or_expression=expression, 4213 into=into, 4214 prefix=prefix, 4215 dialect=dialect, 4216 **opts, 4217 ) 4218 for expression in expressions 4219 ] 4220 4221 existing_expressions = inst.args.get(arg) 4222 if append and existing_expressions: 4223 expressions = existing_expressions + expressions 4224 4225 inst.set(arg, expressions) 4226 return inst 4227 4228 4229def _apply_conjunction_builder( 4230 *expressions, 4231 instance, 4232 arg, 4233 into=None, 4234 append=True, 4235 copy=True, 4236 dialect=None, 4237 **opts, 4238): 4239 expressions = [exp for exp in expressions if exp is not None and exp != ""] 4240 if not expressions: 4241 return instance 4242 4243 inst = _maybe_copy(instance, copy) 4244 4245 existing = inst.args.get(arg) 4246 if append and existing is not None: 4247 expressions = [existing.this if into else existing] + list(expressions) 4248 4249 node = and_(*expressions, dialect=dialect, **opts) 4250 4251 inst.set(arg, into(this=node) if into else node) 4252 return inst 4253 4254 4255def _combine(expressions, operator, dialect=None, **opts): 4256 expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions] 4257 this = expressions[0] 4258 if expressions[1:]: 4259 this = _wrap_operator(this) 4260 for expression in expressions[1:]: 4261 this = operator(this=this, expression=_wrap_operator(expression)) 4262 return this 4263 4264 4265def _wrap_operator(expression): 4266 if isinstance(expression, (And, Or, Not)): 4267 expression = Paren(this=expression) 4268 return expression 4269 4270 4271def union(left, right, distinct=True, dialect=None, **opts): 4272 """ 4273 Initializes a syntax tree from one UNION expression. 4274 4275 Example: 4276 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4277 'SELECT * FROM foo UNION SELECT * FROM bla' 4278 4279 Args: 4280 left (str | Expression): the SQL code string corresponding to the left-hand side. 4281 If an `Expression` instance is passed, it will be used as-is. 4282 right (str | Expression): the SQL code string corresponding to the right-hand side. 4283 If an `Expression` instance is passed, it will be used as-is. 4284 distinct (bool): set the DISTINCT flag if and only if this is true. 4285 dialect (str): the dialect used to parse the input expression. 4286 opts (kwargs): other options to use to parse the input expressions. 4287 Returns: 4288 Union: the syntax tree for the UNION expression. 4289 """ 4290 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4291 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4292 4293 return Union(this=left, expression=right, distinct=distinct) 4294 4295 4296def intersect(left, right, distinct=True, dialect=None, **opts): 4297 """ 4298 Initializes a syntax tree from one INTERSECT expression. 4299 4300 Example: 4301 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4302 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4303 4304 Args: 4305 left (str | Expression): the SQL code string corresponding to the left-hand side. 4306 If an `Expression` instance is passed, it will be used as-is. 4307 right (str | Expression): the SQL code string corresponding to the right-hand side. 4308 If an `Expression` instance is passed, it will be used as-is. 4309 distinct (bool): set the DISTINCT flag if and only if this is true. 4310 dialect (str): the dialect used to parse the input expression. 4311 opts (kwargs): other options to use to parse the input expressions. 4312 Returns: 4313 Intersect: the syntax tree for the INTERSECT expression. 4314 """ 4315 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4316 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4317 4318 return Intersect(this=left, expression=right, distinct=distinct) 4319 4320 4321def except_(left, right, distinct=True, dialect=None, **opts): 4322 """ 4323 Initializes a syntax tree from one EXCEPT expression. 4324 4325 Example: 4326 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4327 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4328 4329 Args: 4330 left (str | Expression): the SQL code string corresponding to the left-hand side. 4331 If an `Expression` instance is passed, it will be used as-is. 4332 right (str | Expression): the SQL code string corresponding to the right-hand side. 4333 If an `Expression` instance is passed, it will be used as-is. 4334 distinct (bool): set the DISTINCT flag if and only if this is true. 4335 dialect (str): the dialect used to parse the input expression. 4336 opts (kwargs): other options to use to parse the input expressions. 4337 Returns: 4338 Except: the syntax tree for the EXCEPT statement. 4339 """ 4340 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4341 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4342 4343 return Except(this=left, expression=right, distinct=distinct) 4344 4345 4346def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4347 """ 4348 Initializes a syntax tree from one or multiple SELECT expressions. 4349 4350 Example: 4351 >>> select("col1", "col2").from_("tbl").sql() 4352 'SELECT col1, col2 FROM tbl' 4353 4354 Args: 4355 *expressions: the SQL code string to parse as the expressions of a 4356 SELECT statement. If an Expression instance is passed, this is used as-is. 4357 dialect: the dialect used to parse the input expressions (in the case that an 4358 input expression is a SQL string). 4359 **opts: other options to use to parse the input expressions (again, in the case 4360 that an input expression is a SQL string). 4361 4362 Returns: 4363 Select: the syntax tree for the SELECT statement. 4364 """ 4365 return Select().select(*expressions, dialect=dialect, **opts) 4366 4367 4368def from_(*expressions, dialect=None, **opts) -> Select: 4369 """ 4370 Initializes a syntax tree from a FROM expression. 4371 4372 Example: 4373 >>> from_("tbl").select("col1", "col2").sql() 4374 'SELECT col1, col2 FROM tbl' 4375 4376 Args: 4377 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4378 SELECT statement. If an Expression instance is passed, this is used as-is. 4379 dialect (str): the dialect used to parse the input expression (in the case that the 4380 input expression is a SQL string). 4381 **opts: other options to use to parse the input expressions (again, in the case 4382 that the input expression is a SQL string). 4383 4384 Returns: 4385 Select: the syntax tree for the SELECT statement. 4386 """ 4387 return Select().from_(*expressions, dialect=dialect, **opts) 4388 4389 4390def update( 4391 table: str | Table, 4392 properties: dict, 4393 where: t.Optional[ExpOrStr] = None, 4394 from_: t.Optional[ExpOrStr] = None, 4395 dialect: DialectType = None, 4396 **opts, 4397) -> Update: 4398 """ 4399 Creates an update statement. 4400 4401 Example: 4402 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4403 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4404 4405 Args: 4406 *properties: dictionary of properties to set which are 4407 auto converted to sql objects eg None -> NULL 4408 where: sql conditional parsed into a WHERE statement 4409 from_: sql statement parsed into a FROM statement 4410 dialect: the dialect used to parse the input expressions. 4411 **opts: other options to use to parse the input expressions. 4412 4413 Returns: 4414 Update: the syntax tree for the UPDATE statement. 4415 """ 4416 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4417 update_expr.set( 4418 "expressions", 4419 [ 4420 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4421 for k, v in properties.items() 4422 ], 4423 ) 4424 if from_: 4425 update_expr.set( 4426 "from", 4427 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4428 ) 4429 if isinstance(where, Condition): 4430 where = Where(this=where) 4431 if where: 4432 update_expr.set( 4433 "where", 4434 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4435 ) 4436 return update_expr 4437 4438 4439def delete( 4440 table: ExpOrStr, 4441 where: t.Optional[ExpOrStr] = None, 4442 returning: t.Optional[ExpOrStr] = None, 4443 dialect: DialectType = None, 4444 **opts, 4445) -> Delete: 4446 """ 4447 Builds a delete statement. 4448 4449 Example: 4450 >>> delete("my_table", where="id > 1").sql() 4451 'DELETE FROM my_table WHERE id > 1' 4452 4453 Args: 4454 where: sql conditional parsed into a WHERE statement 4455 returning: sql conditional parsed into a RETURNING statement 4456 dialect: the dialect used to parse the input expressions. 4457 **opts: other options to use to parse the input expressions. 4458 4459 Returns: 4460 Delete: the syntax tree for the DELETE statement. 4461 """ 4462 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4463 if where: 4464 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4465 if returning: 4466 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4467 return delete_expr 4468 4469 4470def condition(expression, dialect=None, **opts) -> Condition: 4471 """ 4472 Initialize a logical condition expression. 4473 4474 Example: 4475 >>> condition("x=1").sql() 4476 'x = 1' 4477 4478 This is helpful for composing larger logical syntax trees: 4479 >>> where = condition("x=1") 4480 >>> where = where.and_("y=1") 4481 >>> Select().from_("tbl").select("*").where(where).sql() 4482 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4483 4484 Args: 4485 *expression (str | Expression): the SQL code string to parse. 4486 If an Expression instance is passed, this is used as-is. 4487 dialect (str): the dialect used to parse the input expression (in the case that the 4488 input expression is a SQL string). 4489 **opts: other options to use to parse the input expressions (again, in the case 4490 that the input expression is a SQL string). 4491 4492 Returns: 4493 Condition: the expression 4494 """ 4495 return maybe_parse( # type: ignore 4496 expression, 4497 into=Condition, 4498 dialect=dialect, 4499 **opts, 4500 ) 4501 4502 4503def and_(*expressions, dialect=None, **opts) -> And: 4504 """ 4505 Combine multiple conditions with an AND logical operator. 4506 4507 Example: 4508 >>> and_("x=1", and_("y=1", "z=1")).sql() 4509 'x = 1 AND (y = 1 AND z = 1)' 4510 4511 Args: 4512 *expressions (str | Expression): the SQL code strings to parse. 4513 If an Expression instance is passed, this is used as-is. 4514 dialect (str): the dialect used to parse the input expression. 4515 **opts: other options to use to parse the input expressions. 4516 4517 Returns: 4518 And: the new condition 4519 """ 4520 return _combine(expressions, And, dialect, **opts) 4521 4522 4523def or_(*expressions, dialect=None, **opts) -> Or: 4524 """ 4525 Combine multiple conditions with an OR logical operator. 4526 4527 Example: 4528 >>> or_("x=1", or_("y=1", "z=1")).sql() 4529 'x = 1 OR (y = 1 OR z = 1)' 4530 4531 Args: 4532 *expressions (str | Expression): the SQL code strings to parse. 4533 If an Expression instance is passed, this is used as-is. 4534 dialect (str): the dialect used to parse the input expression. 4535 **opts: other options to use to parse the input expressions. 4536 4537 Returns: 4538 Or: the new condition 4539 """ 4540 return _combine(expressions, Or, dialect, **opts) 4541 4542 4543def not_(expression, dialect=None, **opts) -> Not: 4544 """ 4545 Wrap a condition with a NOT operator. 4546 4547 Example: 4548 >>> not_("this_suit='black'").sql() 4549 "NOT this_suit = 'black'" 4550 4551 Args: 4552 expression (str | Expression): the SQL code strings to parse. 4553 If an Expression instance is passed, this is used as-is. 4554 dialect (str): the dialect used to parse the input expression. 4555 **opts: other options to use to parse the input expressions. 4556 4557 Returns: 4558 Not: the new condition 4559 """ 4560 this = condition( 4561 expression, 4562 dialect=dialect, 4563 **opts, 4564 ) 4565 return Not(this=_wrap_operator(this)) 4566 4567 4568def paren(expression) -> Paren: 4569 return Paren(this=expression) 4570 4571 4572SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$") 4573 4574 4575@t.overload 4576def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None: 4577 ... 4578 4579 4580@t.overload 4581def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier: 4582 ... 4583 4584 4585def to_identifier(name, quoted=None): 4586 """Builds an identifier. 4587 4588 Args: 4589 name: The name to turn into an identifier. 4590 quoted: Whether or not force quote the identifier. 4591 4592 Returns: 4593 The identifier ast node. 4594 """ 4595 4596 if name is None: 4597 return None 4598 4599 if isinstance(name, Identifier): 4600 identifier = name 4601 elif isinstance(name, str): 4602 identifier = Identifier( 4603 this=name, 4604 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4605 ) 4606 else: 4607 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4608 return identifier 4609 4610 4611INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*") 4612 4613 4614def to_interval(interval: str | Literal) -> Interval: 4615 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4616 if isinstance(interval, Literal): 4617 if not interval.is_string: 4618 raise ValueError("Invalid interval string.") 4619 4620 interval = interval.this 4621 4622 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4623 4624 if not interval_parts: 4625 raise ValueError("Invalid interval string.") 4626 4627 return Interval( 4628 this=Literal.string(interval_parts.group(1)), 4629 unit=Var(this=interval_parts.group(2)), 4630 ) 4631 4632 4633@t.overload 4634def to_table(sql_path: str | Table, **kwargs) -> Table: 4635 ... 4636 4637 4638@t.overload 4639def to_table(sql_path: None, **kwargs) -> None: 4640 ... 4641 4642 4643def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4644 """ 4645 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4646 If a table is passed in then that table is returned. 4647 4648 Args: 4649 sql_path: a `[catalog].[schema].[table]` string. 4650 4651 Returns: 4652 A table expression. 4653 """ 4654 if sql_path is None or isinstance(sql_path, Table): 4655 return sql_path 4656 if not isinstance(sql_path, str): 4657 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4658 4659 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4660 return Table(this=table_name, db=db, catalog=catalog, **kwargs) 4661 4662 4663def to_column(sql_path: str | Column, **kwargs) -> Column: 4664 """ 4665 Create a column from a `[table].[column]` sql path. Schema is optional. 4666 4667 If a column is passed in then that column is returned. 4668 4669 Args: 4670 sql_path: `[table].[column]` string 4671 Returns: 4672 Table: A column expression 4673 """ 4674 if sql_path is None or isinstance(sql_path, Column): 4675 return sql_path 4676 if not isinstance(sql_path, str): 4677 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4678 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore 4679 4680 4681def alias_( 4682 expression: ExpOrStr, 4683 alias: str | Identifier, 4684 table: bool | t.Sequence[str | Identifier] = False, 4685 quoted: t.Optional[bool] = None, 4686 dialect: DialectType = None, 4687 **opts, 4688): 4689 """Create an Alias expression. 4690 4691 Example: 4692 >>> alias_('foo', 'bar').sql() 4693 'foo AS bar' 4694 4695 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4696 '(SELECT 1, 2) AS bar(a, b)' 4697 4698 Args: 4699 expression: the SQL code strings to parse. 4700 If an Expression instance is passed, this is used as-is. 4701 alias: the alias name to use. If the name has 4702 special characters it is quoted. 4703 table: Whether or not to create a table alias, can also be a list of columns. 4704 quoted: whether or not to quote the alias 4705 dialect: the dialect used to parse the input expression. 4706 **opts: other options to use to parse the input expressions. 4707 4708 Returns: 4709 Alias: the aliased expression 4710 """ 4711 exp = maybe_parse(expression, dialect=dialect, **opts) 4712 alias = to_identifier(alias, quoted=quoted) 4713 4714 if table: 4715 table_alias = TableAlias(this=alias) 4716 exp.set("alias", table_alias) 4717 4718 if not isinstance(table, bool): 4719 for column in table: 4720 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4721 4722 return exp 4723 4724 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4725 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4726 # for the complete Window expression. 4727 # 4728 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4729 4730 if "alias" in exp.arg_types and not isinstance(exp, Window): 4731 exp = exp.copy() 4732 exp.set("alias", alias) 4733 return exp 4734 return Alias(this=exp, alias=alias) 4735 4736 4737def subquery(expression, alias=None, dialect=None, **opts): 4738 """ 4739 Build a subquery expression. 4740 4741 Example: 4742 >>> subquery('select x from tbl', 'bar').select('x').sql() 4743 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4744 4745 Args: 4746 expression (str | Expression): the SQL code strings to parse. 4747 If an Expression instance is passed, this is used as-is. 4748 alias (str | Expression): the alias name to use. 4749 dialect (str): the dialect used to parse the input expression. 4750 **opts: other options to use to parse the input expressions. 4751 4752 Returns: 4753 Select: a new select with the subquery expression included 4754 """ 4755 4756 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4757 return Select().from_(expression, dialect=dialect, **opts) 4758 4759 4760def column( 4761 col: str | Identifier, 4762 table: t.Optional[str | Identifier] = None, 4763 db: t.Optional[str | Identifier] = None, 4764 catalog: t.Optional[str | Identifier] = None, 4765 quoted: t.Optional[bool] = None, 4766) -> Column: 4767 """ 4768 Build a Column. 4769 4770 Args: 4771 col: column name 4772 table: table name 4773 db: db name 4774 catalog: catalog name 4775 quoted: whether or not to force quote each part 4776 Returns: 4777 Column: column instance 4778 """ 4779 return Column( 4780 this=to_identifier(col, quoted=quoted), 4781 table=to_identifier(table, quoted=quoted), 4782 db=to_identifier(db, quoted=quoted), 4783 catalog=to_identifier(catalog, quoted=quoted), 4784 ) 4785 4786 4787def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4788 """Cast an expression to a data type. 4789 4790 Example: 4791 >>> cast('x + 1', 'int').sql() 4792 'CAST(x + 1 AS INT)' 4793 4794 Args: 4795 expression: The expression to cast. 4796 to: The datatype to cast to. 4797 4798 Returns: 4799 A cast node. 4800 """ 4801 expression = maybe_parse(expression, **opts) 4802 return Cast(this=expression, to=DataType.build(to, **opts)) 4803 4804 4805def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4806 """Build a Table. 4807 4808 Args: 4809 table (str | Expression): column name 4810 db (str | Expression): db name 4811 catalog (str | Expression): catalog name 4812 4813 Returns: 4814 Table: table instance 4815 """ 4816 return Table( 4817 this=to_identifier(table, quoted=quoted), 4818 db=to_identifier(db, quoted=quoted), 4819 catalog=to_identifier(catalog, quoted=quoted), 4820 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4821 ) 4822 4823 4824def values( 4825 values: t.Iterable[t.Tuple[t.Any, ...]], 4826 alias: t.Optional[str] = None, 4827 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4828) -> Values: 4829 """Build VALUES statement. 4830 4831 Example: 4832 >>> values([(1, '2')]).sql() 4833 "VALUES (1, '2')" 4834 4835 Args: 4836 values: values statements that will be converted to SQL 4837 alias: optional alias 4838 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4839 If either are provided then an alias is also required. 4840 If a dictionary is provided then the first column of the values will be casted to the expected type 4841 in order to help with type inference. 4842 4843 Returns: 4844 Values: the Values expression object 4845 """ 4846 if columns and not alias: 4847 raise ValueError("Alias is required when providing columns") 4848 table_alias = ( 4849 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4850 if columns 4851 else TableAlias(this=to_identifier(alias) if alias else None) 4852 ) 4853 expressions = [convert(tup) for tup in values] 4854 if columns and isinstance(columns, dict): 4855 types = list(columns.values()) 4856 expressions[0].set( 4857 "expressions", 4858 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4859 ) 4860 return Values( 4861 expressions=expressions, 4862 alias=table_alias, 4863 ) 4864 4865 4866def var(name: t.Optional[ExpOrStr]) -> Var: 4867 """Build a SQL variable. 4868 4869 Example: 4870 >>> repr(var('x')) 4871 '(VAR this: x)' 4872 4873 >>> repr(var(column('x', table='y'))) 4874 '(VAR this: x)' 4875 4876 Args: 4877 name: The name of the var or an expression who's name will become the var. 4878 4879 Returns: 4880 The new variable node. 4881 """ 4882 if not name: 4883 raise ValueError("Cannot convert empty name into var.") 4884 4885 if isinstance(name, Expression): 4886 name = name.name 4887 return Var(this=name) 4888 4889 4890def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4891 """Build ALTER TABLE... RENAME... expression 4892 4893 Args: 4894 old_name: The old name of the table 4895 new_name: The new name of the table 4896 4897 Returns: 4898 Alter table expression 4899 """ 4900 old_table = to_table(old_name) 4901 new_table = to_table(new_name) 4902 return AlterTable( 4903 this=old_table, 4904 actions=[ 4905 RenameTable(this=new_table), 4906 ], 4907 ) 4908 4909 4910def convert(value) -> Expression: 4911 """Convert a python value into an expression object. 4912 4913 Raises an error if a conversion is not possible. 4914 4915 Args: 4916 value (Any): a python object 4917 4918 Returns: 4919 Expression: the equivalent expression object 4920 """ 4921 if isinstance(value, Expression): 4922 return value 4923 if value is None: 4924 return NULL 4925 if isinstance(value, bool): 4926 return Boolean(this=value) 4927 if isinstance(value, str): 4928 return Literal.string(value) 4929 if isinstance(value, float) and math.isnan(value): 4930 return NULL 4931 if isinstance(value, numbers.Number): 4932 return Literal.number(value) 4933 if isinstance(value, tuple): 4934 return Tuple(expressions=[convert(v) for v in value]) 4935 if isinstance(value, list): 4936 return Array(expressions=[convert(v) for v in value]) 4937 if isinstance(value, dict): 4938 return Map( 4939 keys=[convert(k) for k in value], 4940 values=[convert(v) for v in value.values()], 4941 ) 4942 if isinstance(value, datetime.datetime): 4943 datetime_literal = Literal.string( 4944 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4945 ) 4946 return TimeStrToTime(this=datetime_literal) 4947 if isinstance(value, datetime.date): 4948 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4949 return DateStrToDate(this=date_literal) 4950 raise ValueError(f"Cannot convert {value}") 4951 4952 4953def replace_children(expression, fun, *args, **kwargs): 4954 """ 4955 Replace children of an expression with the result of a lambda fun(child) -> exp. 4956 """ 4957 for k, v in expression.args.items(): 4958 is_list_arg = type(v) is list 4959 4960 child_nodes = v if is_list_arg else [v] 4961 new_child_nodes = [] 4962 4963 for cn in child_nodes: 4964 if isinstance(cn, Expression): 4965 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 4966 new_child_nodes.append(child_node) 4967 child_node.parent = expression 4968 child_node.arg_key = k 4969 else: 4970 new_child_nodes.append(cn) 4971 4972 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0) 4973 4974 4975def column_table_names(expression): 4976 """ 4977 Return all table names referenced through columns in an expression. 4978 4979 Example: 4980 >>> import sqlglot 4981 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4982 ['c', 'a'] 4983 4984 Args: 4985 expression (sqlglot.Expression): expression to find table names 4986 4987 Returns: 4988 list: A list of unique names 4989 """ 4990 return list(dict.fromkeys(column.table for column in expression.find_all(Column))) 4991 4992 4993def table_name(table) -> str: 4994 """Get the full name of a table as a string. 4995 4996 Args: 4997 table (exp.Table | str): table expression node or string. 4998 4999 Examples: 5000 >>> from sqlglot import exp, parse_one 5001 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5002 'a.b.c' 5003 5004 Returns: 5005 The table name. 5006 """ 5007 5008 table = maybe_parse(table, into=Table) 5009 5010 if not table: 5011 raise ValueError(f"Cannot parse {table}") 5012 5013 return ".".join( 5014 part 5015 for part in ( 5016 table.text("catalog"), 5017 table.text("db"), 5018 table.name, 5019 ) 5020 if part 5021 ) 5022 5023 5024def replace_tables(expression, mapping): 5025 """Replace all tables in expression according to the mapping. 5026 5027 Args: 5028 expression (sqlglot.Expression): expression node to be transformed and replaced. 5029 mapping (Dict[str, str]): mapping of table names. 5030 5031 Examples: 5032 >>> from sqlglot import exp, parse_one 5033 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5034 'SELECT * FROM c' 5035 5036 Returns: 5037 The mapped expression. 5038 """ 5039 5040 def _replace_tables(node): 5041 if isinstance(node, Table): 5042 new_name = mapping.get(table_name(node)) 5043 if new_name: 5044 return to_table( 5045 new_name, 5046 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5047 ) 5048 return node 5049 5050 return expression.transform(_replace_tables) 5051 5052 5053def replace_placeholders(expression, *args, **kwargs): 5054 """Replace placeholders in an expression. 5055 5056 Args: 5057 expression (sqlglot.Expression): expression node to be transformed and replaced. 5058 args: positional names that will substitute unnamed placeholders in the given order. 5059 kwargs: keyword arguments that will substitute named placeholders. 5060 5061 Examples: 5062 >>> from sqlglot import exp, parse_one 5063 >>> replace_placeholders( 5064 ... parse_one("select * from :tbl where ? = ?"), 5065 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5066 ... ).sql() 5067 "SELECT * FROM foo WHERE str_col = 'b'" 5068 5069 Returns: 5070 The mapped expression. 5071 """ 5072 5073 def _replace_placeholders(node, args, **kwargs): 5074 if isinstance(node, Placeholder): 5075 if node.name: 5076 new_name = kwargs.get(node.name) 5077 if new_name: 5078 return convert(new_name) 5079 else: 5080 try: 5081 return convert(next(args)) 5082 except StopIteration: 5083 pass 5084 return node 5085 5086 return expression.transform(_replace_placeholders, iter(args), **kwargs) 5087 5088 5089def expand( 5090 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5091) -> Expression: 5092 """Transforms an expression by expanding all referenced sources into subqueries. 5093 5094 Examples: 5095 >>> from sqlglot import parse_one 5096 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5097 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5098 5099 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5100 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5101 5102 Args: 5103 expression: The expression to expand. 5104 sources: A dictionary of name to Subqueryables. 5105 copy: Whether or not to copy the expression during transformation. Defaults to True. 5106 5107 Returns: 5108 The transformed expression. 5109 """ 5110 5111 def _expand(node: Expression): 5112 if isinstance(node, Table): 5113 name = table_name(node) 5114 source = sources.get(name) 5115 if source: 5116 subquery = source.subquery(node.alias or name) 5117 subquery.comments = [f"source: {name}"] 5118 return subquery.transform(_expand, copy=False) 5119 return node 5120 5121 return expression.transform(_expand, copy=copy) 5122 5123 5124def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5125 """ 5126 Returns a Func expression. 5127 5128 Examples: 5129 >>> func("abs", 5).sql() 5130 'ABS(5)' 5131 5132 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5133 'CAST(5 AS DOUBLE)' 5134 5135 Args: 5136 name: the name of the function to build. 5137 args: the args used to instantiate the function of interest. 5138 dialect: the source dialect. 5139 kwargs: the kwargs used to instantiate the function of interest. 5140 5141 Note: 5142 The arguments `args` and `kwargs` are mutually exclusive. 5143 5144 Returns: 5145 An instance of the function of interest, or an anonymous function, if `name` doesn't 5146 correspond to an existing `sqlglot.expressions.Func` class. 5147 """ 5148 if args and kwargs: 5149 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5150 5151 from sqlglot.dialects.dialect import Dialect 5152 5153 converted = [convert(arg) for arg in args] 5154 kwargs = {key: convert(value) for key, value in kwargs.items()} 5155 5156 parser = Dialect.get_or_raise(dialect)().parser() 5157 from_args_list = parser.FUNCTIONS.get(name.upper()) 5158 5159 if from_args_list: 5160 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5161 else: 5162 kwargs = kwargs or {"expressions": converted} 5163 function = Anonymous(this=name, **kwargs) 5164 5165 for error_message in function.error_messages(converted): 5166 raise ValueError(error_message) 5167 5168 return function 5169 5170 5171def true(): 5172 """ 5173 Returns a true Boolean expression. 5174 """ 5175 return Boolean(this=True) 5176 5177 5178def false(): 5179 """ 5180 Returns a false Boolean expression. 5181 """ 5182 return Boolean(this=False) 5183 5184 5185def null(): 5186 """ 5187 Returns a Null expression. 5188 """ 5189 return Null() 5190 5191 5192# TODO: deprecate this 5193TRUE = Boolean(this=True) 5194FALSE = Boolean(this=False) 5195NULL = Null()
57class Expression(metaclass=_Expression): 58 """ 59 The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary 60 context, such as its child expressions, their names (arg keys), and whether a given child expression 61 is optional or not. 62 63 Attributes: 64 key: a unique key for each class in the Expression hierarchy. This is useful for hashing 65 and representing expressions as strings. 66 arg_types: determines what arguments (child nodes) are supported by an expression. It 67 maps arg keys to booleans that indicate whether the corresponding args are optional. 68 69 Example: 70 >>> class Foo(Expression): 71 ... arg_types = {"this": True, "expression": False} 72 73 The above definition informs us that Foo is an Expression that requires an argument called 74 "this" and may also optionally receive an argument called "expression". 75 76 Args: 77 args: a mapping used for retrieving the arguments of an expression, given their arg keys. 78 parent: a reference to the parent expression (or None, in case of root expressions). 79 arg_key: the arg key an expression is associated with, i.e. the name its parent expression 80 uses to refer to it. 81 comments: a list of comments that are associated with a given expression. This is used in 82 order to preserve comments when transpiling SQL code. 83 _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the 84 optimizer, in order to enable some transformations that require type information. 85 """ 86 87 key = "expression" 88 arg_types = {"this": True} 89 __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash") 90 91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value) 102 103 def __eq__(self, other) -> bool: 104 return type(self) is type(other) and hash(self) == hash(other) 105 106 @property 107 def hashable_args(self) -> t.Any: 108 args = (self.args.get(k) for k in self.arg_types) 109 110 return tuple( 111 (tuple(_norm_arg(a) for a in arg) if arg else None) 112 if type(arg) is list 113 else (_norm_arg(arg) if arg is not None and arg is not False else None) 114 for arg in args 115 ) 116 117 def __hash__(self) -> int: 118 if self._hash is not None: 119 return self._hash 120 121 return hash((self.__class__, self.hashable_args)) 122 123 @property 124 def this(self): 125 """ 126 Retrieves the argument with key "this". 127 """ 128 return self.args.get("this") 129 130 @property 131 def expression(self): 132 """ 133 Retrieves the argument with key "expression". 134 """ 135 return self.args.get("expression") 136 137 @property 138 def expressions(self): 139 """ 140 Retrieves the argument with key "expressions". 141 """ 142 return self.args.get("expressions") or [] 143 144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return "" 157 158 @property 159 def is_string(self) -> bool: 160 """ 161 Checks whether a Literal expression is a string. 162 """ 163 return isinstance(self, Literal) and self.args["is_string"] 164 165 @property 166 def is_number(self) -> bool: 167 """ 168 Checks whether a Literal expression is a number. 169 """ 170 return isinstance(self, Literal) and not self.args["is_string"] 171 172 @property 173 def is_int(self) -> bool: 174 """ 175 Checks whether a Literal expression is an integer. 176 """ 177 if self.is_number: 178 try: 179 int(self.name) 180 return True 181 except ValueError: 182 pass 183 return False 184 185 @property 186 def is_star(self) -> bool: 187 """Checks whether an expression is a star.""" 188 return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star)) 189 190 @property 191 def alias(self) -> str: 192 """ 193 Returns the alias of the expression, or an empty string if it's not aliased. 194 """ 195 if isinstance(self.args.get("alias"), TableAlias): 196 return self.args["alias"].name 197 return self.text("alias") 198 199 @property 200 def name(self) -> str: 201 return self.text("this") 202 203 @property 204 def alias_or_name(self): 205 return self.alias or self.name 206 207 @property 208 def output_name(self): 209 """ 210 Name of the output column if this expression is a selection. 211 212 If the Expression has no output name, an empty string is returned. 213 214 Example: 215 >>> from sqlglot import parse_one 216 >>> parse_one("SELECT a").expressions[0].output_name 217 'a' 218 >>> parse_one("SELECT b AS c").expressions[0].output_name 219 'c' 220 >>> parse_one("SELECT 1 + 2").expressions[0].output_name 221 '' 222 """ 223 return "" 224 225 @property 226 def type(self) -> t.Optional[DataType]: 227 return self._type 228 229 @type.setter 230 def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None: 231 if dtype and not isinstance(dtype, DataType): 232 dtype = DataType.build(dtype) 233 self._type = dtype # type: ignore 234 235 @property 236 def meta(self) -> t.Dict[str, t.Any]: 237 if self._meta is None: 238 self._meta = {} 239 return self._meta 240 241 def __deepcopy__(self, memo): 242 copy = self.__class__(**deepcopy(self.args)) 243 if self.comments is not None: 244 copy.comments = deepcopy(self.comments) 245 246 if self._type is not None: 247 copy._type = self._type.copy() 248 249 if self._meta is not None: 250 copy._meta = deepcopy(self._meta) 251 252 return copy 253 254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new 261 262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value) 274 275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value) 285 286 def _set_parent(self, arg_key, value): 287 if hasattr(value, "parent"): 288 value.parent = self 289 value.arg_key = arg_key 290 elif type(value) is list: 291 for v in value: 292 if hasattr(v, "parent"): 293 v.parent = self 294 v.arg_key = arg_key 295 296 @property 297 def depth(self): 298 """ 299 Returns the depth of this tree. 300 """ 301 if self.parent: 302 return self.parent.depth + 1 303 return 0 304 305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs 315 316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None) 328 329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression 343 344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor) 358 359 @property 360 def parent_select(self): 361 """ 362 Returns the parent select statement. 363 """ 364 return self.find_ancestor(Select) 365 366 @property 367 def same_parent(self): 368 """Returns if the parent is the same class as itself.""" 369 return type(self.parent) is self.__class__ 370 371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression 379 380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune) 397 398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune) 413 414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k)) 433 434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression 442 443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self 450 451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions()) 456 457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node 466 467 def __str__(self): 468 return self.sql() 469 470 def __repr__(self): 471 return self._to_s() 472 473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts) 487 488 def _to_s(self, hide_missing: bool = True, level: int = 0) -> str: 489 indent = "" if not level else "\n" 490 indent += "".join([" "] * level) 491 left = f"({self.key.upper()} " 492 493 args: t.Dict[str, t.Any] = { 494 k: ", ".join( 495 v._to_s(hide_missing=hide_missing, level=level + 1) 496 if hasattr(v, "_to_s") 497 else str(v) 498 for v in ensure_list(vs) 499 if v is not None 500 ) 501 for k, vs in self.args.items() 502 } 503 args["comments"] = self.comments 504 args["type"] = self.type 505 args = {k: v for k, v in args.items() if v or not hide_missing} 506 507 right = ", ".join(f"{k}: {v}" for k, v in args.items()) 508 right += ")" 509 510 return indent + left + right 511 512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node 538 539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression 565 566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self 575 576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self 592 593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors 626 627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self) 634 635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.
Attributes:
- key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
- arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression): ... arg_types = {"this": True, "expression": False}The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".
Arguments:
- args: a mapping used for retrieving the arguments of an expression, given their arg keys.
- parent: a reference to the parent expression (or None, in case of root expressions).
- arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
- comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
- _type: the
sqlglot.expressions.DataTypetype of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
91 def __init__(self, **args: t.Any): 92 self.args: t.Dict[str, t.Any] = args 93 self.parent: t.Optional[Expression] = None 94 self.arg_key: t.Optional[str] = None 95 self.comments: t.Optional[t.List[str]] = None 96 self._type: t.Optional[DataType] = None 97 self._meta: t.Optional[t.Dict[str, t.Any]] = None 98 self._hash: t.Optional[int] = None 99 100 for arg_key, value in self.args.items(): 101 self._set_parent(arg_key, value)
144 def text(self, key) -> str: 145 """ 146 Returns a textual representation of the argument corresponding to "key". This can only be used 147 for args that are strings or leaf Expression instances, such as identifiers and literals. 148 """ 149 field = self.args.get(key) 150 if isinstance(field, str): 151 return field 152 if isinstance(field, (Identifier, Literal, Var)): 153 return field.this 154 if isinstance(field, (Star, Null)): 155 return field.name 156 return ""
Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
254 def copy(self): 255 """ 256 Returns a deep copy of the expression. 257 """ 258 new = deepcopy(self) 259 new.parent = self.parent 260 return new
Returns a deep copy of the expression.
262 def append(self, arg_key, value): 263 """ 264 Appends value to arg_key if it's a list or sets it as a new list. 265 266 Args: 267 arg_key (str): name of the list expression arg 268 value (Any): value to append to the list 269 """ 270 if not isinstance(self.args.get(arg_key), list): 271 self.args[arg_key] = [] 272 self.args[arg_key].append(value) 273 self._set_parent(arg_key, value)
Appends value to arg_key if it's a list or sets it as a new list.
Arguments:
- arg_key (str): name of the list expression arg
- value (Any): value to append to the list
275 def set(self, arg_key, value): 276 """ 277 Sets `arg_key` to `value`. 278 279 Args: 280 arg_key (str): name of the expression arg. 281 value: value to set the arg to. 282 """ 283 self.args[arg_key] = value 284 self._set_parent(arg_key, value)
Sets arg_key to value.
Arguments:
- arg_key (str): name of the expression arg.
- value: value to set the arg to.
305 def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]: 306 """Yields the key and expression for all arguments, exploding list args.""" 307 for k, vs in self.args.items(): 308 if type(vs) is list: 309 for v in vs: 310 if hasattr(v, "parent"): 311 yield k, v 312 else: 313 if hasattr(vs, "parent"): 314 yield k, vs
Yields the key and expression for all arguments, exploding list args.
316 def find(self, *expression_types: t.Type[E], bfs=True) -> E | None: 317 """ 318 Returns the first node in this tree which matches at least one of 319 the specified types. 320 321 Args: 322 expression_types: the expression type(s) to match. 323 324 Returns: 325 The node which matches the criteria or None if no such node was found. 326 """ 327 return next(self.find_all(*expression_types, bfs=bfs), None)
Returns the first node in this tree which matches at least one of the specified types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The node which matches the criteria or None if no such node was found.
329 def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]: 330 """ 331 Returns a generator object which visits all nodes in this tree and only 332 yields those that match at least one of the specified expression types. 333 334 Args: 335 expression_types: the expression type(s) to match. 336 337 Returns: 338 The generator object. 339 """ 340 for expression, *_ in self.walk(bfs=bfs): 341 if isinstance(expression, expression_types): 342 yield expression
Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The generator object.
344 def find_ancestor(self, *expression_types: t.Type[E]) -> E | None: 345 """ 346 Returns a nearest parent matching expression_types. 347 348 Args: 349 expression_types: the expression type(s) to match. 350 351 Returns: 352 The parent node. 353 """ 354 ancestor = self.parent 355 while ancestor and not isinstance(ancestor, expression_types): 356 ancestor = ancestor.parent 357 return t.cast(E, ancestor)
Returns a nearest parent matching expression_types.
Arguments:
- expression_types: the expression type(s) to match.
Returns:
The parent node.
371 def root(self) -> Expression: 372 """ 373 Returns the root expression of this tree. 374 """ 375 expression = self 376 while expression.parent: 377 expression = expression.parent 378 return expression
Returns the root expression of this tree.
380 def walk(self, bfs=True, prune=None): 381 """ 382 Returns a generator object which visits all nodes in this tree. 383 384 Args: 385 bfs (bool): if set to True the BFS traversal order will be applied, 386 otherwise the DFS traversal will be used instead. 387 prune ((node, parent, arg_key) -> bool): callable that returns True if 388 the generator should stop traversing this branch of the tree. 389 390 Returns: 391 the generator object. 392 """ 393 if bfs: 394 yield from self.bfs(prune=prune) 395 else: 396 yield from self.dfs(prune=prune)
Returns a generator object which visits all nodes in this tree.
Arguments:
- bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
- prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:
the generator object.
398 def dfs(self, parent=None, key=None, prune=None): 399 """ 400 Returns a generator object which visits all nodes in this tree in 401 the DFS (Depth-first) order. 402 403 Returns: 404 The generator object. 405 """ 406 parent = parent or self.parent 407 yield self, parent, key 408 if prune and prune(self, parent, key): 409 return 410 411 for k, v in self.iter_expressions(): 412 yield from v.dfs(self, k, prune)
Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.
Returns:
The generator object.
414 def bfs(self, prune=None): 415 """ 416 Returns a generator object which visits all nodes in this tree in 417 the BFS (Breadth-first) order. 418 419 Returns: 420 The generator object. 421 """ 422 queue = deque([(self, self.parent, None)]) 423 424 while queue: 425 item, parent, key = queue.popleft() 426 427 yield item, parent, key 428 if prune and prune(item, parent, key): 429 continue 430 431 for k, v in item.iter_expressions(): 432 queue.append((v, item, k))
Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.
Returns:
The generator object.
434 def unnest(self): 435 """ 436 Returns the first non parenthesis child or self. 437 """ 438 expression = self 439 while type(expression) is Paren: 440 expression = expression.this 441 return expression
Returns the first non parenthesis child or self.
443 def unalias(self): 444 """ 445 Returns the inner expression if this is an Alias. 446 """ 447 if isinstance(self, Alias): 448 return self.this 449 return self
Returns the inner expression if this is an Alias.
451 def unnest_operands(self): 452 """ 453 Returns unnested operands as a tuple. 454 """ 455 return tuple(arg.unnest() for _, arg in self.iter_expressions())
Returns unnested operands as a tuple.
457 def flatten(self, unnest=True): 458 """ 459 Returns a generator which yields child nodes who's parents are the same class. 460 461 A AND B AND C -> [A, B, C] 462 """ 463 for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__): 464 if not type(node) is self.__class__: 465 yield node.unnest() if unnest else node
Returns a generator which yields child nodes who's parents are the same class.
A AND B AND C -> [A, B, C]
473 def sql(self, dialect: DialectType = None, **opts) -> str: 474 """ 475 Returns SQL string representation of this tree. 476 477 Args: 478 dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql"). 479 opts: other `sqlglot.generator.Generator` options. 480 481 Returns: 482 The SQL string. 483 """ 484 from sqlglot.dialects import Dialect 485 486 return Dialect.get_or_raise(dialect)().generate(self, **opts)
Returns SQL string representation of this tree.
Arguments:
- dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
- opts: other
sqlglot.generator.Generatoroptions.
Returns:
The SQL string.
512 def transform(self, fun, *args, copy=True, **kwargs): 513 """ 514 Recursively visits all tree nodes (excluding already transformed ones) 515 and applies the given transformation function to each node. 516 517 Args: 518 fun (function): a function which takes a node as an argument and returns a 519 new transformed node or the same node without modifications. If the function 520 returns None, then the corresponding node will be removed from the syntax tree. 521 copy (bool): if set to True a new tree instance is constructed, otherwise the tree is 522 modified in place. 523 524 Returns: 525 The transformed tree. 526 """ 527 node = self.copy() if copy else self 528 new_node = fun(node, *args, **kwargs) 529 530 if new_node is None or not isinstance(new_node, Expression): 531 return new_node 532 if new_node is not node: 533 new_node.parent = node.parent 534 return new_node 535 536 replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs)) 537 return new_node
Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.
Arguments:
- fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
- copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:
The transformed tree.
539 def replace(self, expression): 540 """ 541 Swap out this expression with a new expression. 542 543 For example:: 544 545 >>> tree = Select().select("x").from_("tbl") 546 >>> tree.find(Column).replace(Column(this="y")) 547 (COLUMN this: y) 548 >>> tree.sql() 549 'SELECT y FROM tbl' 550 551 Args: 552 expression (Expression|None): new node 553 554 Returns: 555 The new expression or expressions. 556 """ 557 if not self.parent: 558 return expression 559 560 parent = self.parent 561 self.parent = None 562 563 replace_children(parent, lambda child: expression if child is self else child) 564 return expression
Swap out this expression with a new expression.
For example::
>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
- expression (Expression|None): new node
Returns:
The new expression or expressions.
566 def pop(self): 567 """ 568 Remove this expression from its AST. 569 570 Returns: 571 The popped expression. 572 """ 573 self.replace(None) 574 return self
Remove this expression from its AST.
Returns:
The popped expression.
576 def assert_is(self, type_): 577 """ 578 Assert that this `Expression` is an instance of `type_`. 579 580 If it is NOT an instance of `type_`, this raises an assertion error. 581 Otherwise, this returns this expression. 582 583 Examples: 584 This is useful for type security in chained expressions: 585 586 >>> import sqlglot 587 >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 588 'SELECT x, z FROM y' 589 """ 590 assert isinstance(self, type_) 591 return self
Assert that this Expression is an instance of type_.
If it is NOT an instance of type_, this raises an assertion error.
Otherwise, this returns this expression.
Examples:
This is useful for type security in chained expressions:
>>> import sqlglot >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql() 'SELECT x, z FROM y'
593 def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]: 594 """ 595 Checks if this expression is valid (e.g. all mandatory args are set). 596 597 Args: 598 args: a sequence of values that were used to instantiate a Func expression. This is used 599 to check that the provided arguments don't exceed the function argument limit. 600 601 Returns: 602 A list of error messages for all possible errors that were found. 603 """ 604 errors: t.List[str] = [] 605 606 for k in self.args: 607 if k not in self.arg_types: 608 errors.append(f"Unexpected keyword: '{k}' for {self.__class__}") 609 for k, mandatory in self.arg_types.items(): 610 v = self.args.get(k) 611 if mandatory and (v is None or (isinstance(v, list) and not v)): 612 errors.append(f"Required keyword: '{k}' missing for {self.__class__}") 613 614 if ( 615 args 616 and isinstance(self, Func) 617 and len(args) > len(self.arg_types) 618 and not self.is_var_len_args 619 ): 620 errors.append( 621 f"The number of provided arguments ({len(args)}) is greater than " 622 f"the maximum number of supported arguments ({len(self.arg_types)})" 623 ) 624 625 return errors
Checks if this expression is valid (e.g. all mandatory args are set).
Arguments:
- args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:
A list of error messages for all possible errors that were found.
627 def dump(self): 628 """ 629 Dump this Expression to a JSON-serializable dict. 630 """ 631 from sqlglot.serde import dump 632 633 return dump(self)
Dump this Expression to a JSON-serializable dict.
635 @classmethod 636 def load(cls, obj): 637 """ 638 Load a dict (as returned by `Expression.dump`) into an Expression instance. 639 """ 640 from sqlglot.serde import load 641 642 return load(obj)
Load a dict (as returned by Expression.dump) into an Expression instance.
653class Condition(Expression): 654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts) 672 673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts) 691 692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self)
654 def and_(self, *expressions, dialect=None, **opts): 655 """ 656 AND this condition with one or multiple expressions. 657 658 Example: 659 >>> condition("x=1").and_("y=1").sql() 660 'x = 1 AND y = 1' 661 662 Args: 663 *expressions (str | Expression): the SQL code strings to parse. 664 If an `Expression` instance is passed, it will be used as-is. 665 dialect (str): the dialect used to parse the input expression. 666 opts (kwargs): other options to use to parse the input expressions. 667 668 Returns: 669 And: the new condition. 670 """ 671 return and_(self, *expressions, dialect=dialect, **opts)
AND this condition with one or multiple expressions.
Example:
>>> condition("x=1").and_("y=1").sql() 'x = 1 AND y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
And: the new condition.
673 def or_(self, *expressions, dialect=None, **opts): 674 """ 675 OR this condition with one or multiple expressions. 676 677 Example: 678 >>> condition("x=1").or_("y=1").sql() 679 'x = 1 OR y = 1' 680 681 Args: 682 *expressions (str | Expression): the SQL code strings to parse. 683 If an `Expression` instance is passed, it will be used as-is. 684 dialect (str): the dialect used to parse the input expression. 685 opts (kwargs): other options to use to parse the input expressions. 686 687 Returns: 688 Or: the new condition. 689 """ 690 return or_(self, *expressions, dialect=dialect, **opts)
OR this condition with one or multiple expressions.
Example:
>>> condition("x=1").or_("y=1").sql() 'x = 1 OR y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Or: the new condition.
692 def not_(self): 693 """ 694 Wrap this condition with NOT. 695 696 Example: 697 >>> condition("x=1").not_().sql() 698 'NOT x = 1' 699 700 Returns: 701 Not: the new condition. 702 """ 703 return not_(self)
Wrap this condition with NOT.
Example:
>>> condition("x=1").not_().sql() 'NOT x = 1'
Returns:
Not: the new condition.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Relationships like x = y, x > 1, x >= y.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
710class DerivedTable(Expression): 711 @property 712 def alias_column_names(self): 713 table_alias = self.args.get("alias") 714 if not table_alias: 715 return [] 716 column_list = table_alias.assert_is(TableAlias).args.get("columns") or [] 717 return [c.name for c in column_list] 718 719 @property 720 def selects(self): 721 alias = self.args.get("alias") 722 723 if alias: 724 return alias.columns 725 return [] 726 727 @property 728 def named_selects(self): 729 return [select.output_name for select in self.selects]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
732class Unionable(Expression): 733 def union(self, expression, distinct=True, dialect=None, **opts): 734 """ 735 Builds a UNION expression. 736 737 Example: 738 >>> import sqlglot 739 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 740 'SELECT * FROM foo UNION SELECT * FROM bla' 741 742 Args: 743 expression (str | Expression): the SQL code string. 744 If an `Expression` instance is passed, it will be used as-is. 745 distinct (bool): set the DISTINCT flag if and only if this is true. 746 dialect (str): the dialect used to parse the input expression. 747 opts (kwargs): other options to use to parse the input expressions. 748 Returns: 749 Union: the Union expression. 750 """ 751 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 752 753 def intersect(self, expression, distinct=True, dialect=None, **opts): 754 """ 755 Builds an INTERSECT expression. 756 757 Example: 758 >>> import sqlglot 759 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 760 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 761 762 Args: 763 expression (str | Expression): the SQL code string. 764 If an `Expression` instance is passed, it will be used as-is. 765 distinct (bool): set the DISTINCT flag if and only if this is true. 766 dialect (str): the dialect used to parse the input expression. 767 opts (kwargs): other options to use to parse the input expressions. 768 Returns: 769 Intersect: the Intersect expression 770 """ 771 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts) 772 773 def except_(self, expression, distinct=True, dialect=None, **opts): 774 """ 775 Builds an EXCEPT expression. 776 777 Example: 778 >>> import sqlglot 779 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 780 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 781 782 Args: 783 expression (str | Expression): the SQL code string. 784 If an `Expression` instance is passed, it will be used as-is. 785 distinct (bool): set the DISTINCT flag if and only if this is true. 786 dialect (str): the dialect used to parse the input expression. 787 opts (kwargs): other options to use to parse the input expressions. 788 Returns: 789 Except: the Except expression 790 """ 791 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
733 def union(self, expression, distinct=True, dialect=None, **opts): 734 """ 735 Builds a UNION expression. 736 737 Example: 738 >>> import sqlglot 739 >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 740 'SELECT * FROM foo UNION SELECT * FROM bla' 741 742 Args: 743 expression (str | Expression): the SQL code string. 744 If an `Expression` instance is passed, it will be used as-is. 745 distinct (bool): set the DISTINCT flag if and only if this is true. 746 dialect (str): the dialect used to parse the input expression. 747 opts (kwargs): other options to use to parse the input expressions. 748 Returns: 749 Union: the Union expression. 750 """ 751 return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds a UNION expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the Union expression.
753 def intersect(self, expression, distinct=True, dialect=None, **opts): 754 """ 755 Builds an INTERSECT expression. 756 757 Example: 758 >>> import sqlglot 759 >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 760 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 761 762 Args: 763 expression (str | Expression): the SQL code string. 764 If an `Expression` instance is passed, it will be used as-is. 765 distinct (bool): set the DISTINCT flag if and only if this is true. 766 dialect (str): the dialect used to parse the input expression. 767 opts (kwargs): other options to use to parse the input expressions. 768 Returns: 769 Intersect: the Intersect expression 770 """ 771 return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an INTERSECT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the Intersect expression
773 def except_(self, expression, distinct=True, dialect=None, **opts): 774 """ 775 Builds an EXCEPT expression. 776 777 Example: 778 >>> import sqlglot 779 >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 780 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 781 782 Args: 783 expression (str | Expression): the SQL code string. 784 If an `Expression` instance is passed, it will be used as-is. 785 distinct (bool): set the DISTINCT flag if and only if this is true. 786 dialect (str): the dialect used to parse the input expression. 787 opts (kwargs): other options to use to parse the input expressions. 788 Returns: 789 Except: the Except expression 790 """ 791 return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
Builds an EXCEPT expression.
Example:
>>> import sqlglot >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- expression (str | Expression): the SQL code string.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the Except expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
798class Cache(Expression): 799 arg_types = { 800 "with": False, 801 "this": True, 802 "lazy": False, 803 "options": False, 804 "expression": False, 805 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
812class Create(Expression): 813 arg_types = { 814 "with": False, 815 "this": True, 816 "kind": True, 817 "expression": False, 818 "exists": False, 819 "properties": False, 820 "replace": False, 821 "unique": False, 822 "indexes": False, 823 "no_schema_binding": False, 824 "begin": False, 825 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
840class SetItem(Expression): 841 arg_types = { 842 "this": False, 843 "expressions": False, 844 "kind": False, 845 "collate": False, # MySQL SET NAMES statement 846 "global": False, 847 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
850class Show(Expression): 851 arg_types = { 852 "this": True, 853 "target": False, 854 "offset": False, 855 "limit": False, 856 "like": False, 857 "where": False, 858 "db": False, 859 "full": False, 860 "mutex": False, 861 "query": False, 862 "channel": False, 863 "global": False, 864 "log": False, 865 "position": False, 866 "types": False, 867 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
870class UserDefinedFunction(Expression): 871 arg_types = {"this": True, "expressions": False, "wrapped": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
878class With(Expression): 879 arg_types = {"expressions": True, "recursive": False} 880 881 @property 882 def recursive(self) -> bool: 883 return bool(self.args.get("recursive"))
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
894class TableAlias(Expression): 895 arg_types = {"this": False, "columns": False} 896 897 @property 898 def columns(self): 899 return self.args.get("columns") or []
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
914class Column(Condition): 915 arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False} 916 917 @property 918 def table(self) -> str: 919 return self.text("table") 920 921 @property 922 def db(self) -> str: 923 return self.text("db") 924 925 @property 926 def catalog(self) -> str: 927 return self.text("catalog") 928 929 @property 930 def output_name(self) -> str: 931 return self.name 932 933 @property 934 def parts(self) -> t.List[Identifier]: 935 """Return the parts of a column in order catalog, db, table, name.""" 936 return [part for part in reversed(list(self.args.values())) if part] 937 938 def to_dot(self) -> Dot: 939 """Converts the column into a dot expression.""" 940 parts = self.parts 941 parent = self.parent 942 943 while parent: 944 if isinstance(parent, Dot): 945 parts.append(parent.expression) 946 parent = parent.parent 947 948 return Dot.build(parts)
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Return the parts of a column in order catalog, db, table, name.
938 def to_dot(self) -> Dot: 939 """Converts the column into a dot expression.""" 940 parts = self.parts 941 parent = self.parent 942 943 while parent: 944 if isinstance(parent, Dot): 945 parts.append(parent.expression) 946 parent = parent.parent 947 948 return Dot.build(parts)
Converts the column into a dot expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
955class ColumnDef(Expression): 956 arg_types = { 957 "this": True, 958 "kind": False, 959 "constraints": False, 960 "exists": False, 961 "position": False, 962 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
965class AlterColumn(Expression): 966 arg_types = { 967 "this": True, 968 "dtype": False, 969 "collate": False, 970 "using": False, 971 "default": False, 972 "drop": False, 973 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
984class Comment(Expression): 985 arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1036class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind): 1037 # this: True -> ALWAYS, this: False -> BY DEFAULT 1038 arg_types = { 1039 "this": False, 1040 "start": False, 1041 "increment": False, 1042 "minvalue": False, 1043 "maxvalue": False, 1044 "cycle": False, 1045 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1085class Delete(Expression): 1086 arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False} 1087 1088 def delete( 1089 self, 1090 table: ExpOrStr, 1091 dialect: DialectType = None, 1092 copy: bool = True, 1093 **opts, 1094 ) -> Delete: 1095 """ 1096 Create a DELETE expression or replace the table on an existing DELETE expression. 1097 1098 Example: 1099 >>> delete("tbl").sql() 1100 'DELETE FROM tbl' 1101 1102 Args: 1103 table: the table from which to delete. 1104 dialect: the dialect used to parse the input expression. 1105 copy: if `False`, modify this expression instance in-place. 1106 opts: other options to use to parse the input expressions. 1107 1108 Returns: 1109 Delete: the modified expression. 1110 """ 1111 return _apply_builder( 1112 expression=table, 1113 instance=self, 1114 arg="this", 1115 dialect=dialect, 1116 into=Table, 1117 copy=copy, 1118 **opts, 1119 ) 1120 1121 def where( 1122 self, 1123 *expressions: ExpOrStr, 1124 append: bool = True, 1125 dialect: DialectType = None, 1126 copy: bool = True, 1127 **opts, 1128 ) -> Delete: 1129 """ 1130 Append to or set the WHERE expressions. 1131 1132 Example: 1133 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1134 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1135 1136 Args: 1137 *expressions: the SQL code strings to parse. 1138 If an `Expression` instance is passed, it will be used as-is. 1139 Multiple expressions are combined with an AND operator. 1140 append: if `True`, AND the new expressions to any existing expression. 1141 Otherwise, this resets the expression. 1142 dialect: the dialect used to parse the input expressions. 1143 copy: if `False`, modify this expression instance in-place. 1144 opts: other options to use to parse the input expressions. 1145 1146 Returns: 1147 Delete: the modified expression. 1148 """ 1149 return _apply_conjunction_builder( 1150 *expressions, 1151 instance=self, 1152 arg="where", 1153 append=append, 1154 into=Where, 1155 dialect=dialect, 1156 copy=copy, 1157 **opts, 1158 ) 1159 1160 def returning( 1161 self, 1162 expression: ExpOrStr, 1163 dialect: DialectType = None, 1164 copy: bool = True, 1165 **opts, 1166 ) -> Delete: 1167 """ 1168 Set the RETURNING expression. Not supported by all dialects. 1169 1170 Example: 1171 >>> delete("tbl").returning("*", dialect="postgres").sql() 1172 'DELETE FROM tbl RETURNING *' 1173 1174 Args: 1175 expression: the SQL code strings to parse. 1176 If an `Expression` instance is passed, it will be used as-is. 1177 dialect: the dialect used to parse the input expressions. 1178 copy: if `False`, modify this expression instance in-place. 1179 opts: other options to use to parse the input expressions. 1180 1181 Returns: 1182 Delete: the modified expression. 1183 """ 1184 return _apply_builder( 1185 expression=expression, 1186 instance=self, 1187 arg="returning", 1188 prefix="RETURNING", 1189 dialect=dialect, 1190 copy=copy, 1191 into=Returning, 1192 **opts, 1193 )
1088 def delete( 1089 self, 1090 table: ExpOrStr, 1091 dialect: DialectType = None, 1092 copy: bool = True, 1093 **opts, 1094 ) -> Delete: 1095 """ 1096 Create a DELETE expression or replace the table on an existing DELETE expression. 1097 1098 Example: 1099 >>> delete("tbl").sql() 1100 'DELETE FROM tbl' 1101 1102 Args: 1103 table: the table from which to delete. 1104 dialect: the dialect used to parse the input expression. 1105 copy: if `False`, modify this expression instance in-place. 1106 opts: other options to use to parse the input expressions. 1107 1108 Returns: 1109 Delete: the modified expression. 1110 """ 1111 return _apply_builder( 1112 expression=table, 1113 instance=self, 1114 arg="this", 1115 dialect=dialect, 1116 into=Table, 1117 copy=copy, 1118 **opts, 1119 )
Create a DELETE expression or replace the table on an existing DELETE expression.
Example:
>>> delete("tbl").sql() 'DELETE FROM tbl'
Arguments:
- table: the table from which to delete.
- dialect: the dialect used to parse the input expression.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1121 def where( 1122 self, 1123 *expressions: ExpOrStr, 1124 append: bool = True, 1125 dialect: DialectType = None, 1126 copy: bool = True, 1127 **opts, 1128 ) -> Delete: 1129 """ 1130 Append to or set the WHERE expressions. 1131 1132 Example: 1133 >>> delete("tbl").where("x = 'a' OR x < 'b'").sql() 1134 "DELETE FROM tbl WHERE x = 'a' OR x < 'b'" 1135 1136 Args: 1137 *expressions: the SQL code strings to parse. 1138 If an `Expression` instance is passed, it will be used as-is. 1139 Multiple expressions are combined with an AND operator. 1140 append: if `True`, AND the new expressions to any existing expression. 1141 Otherwise, this resets the expression. 1142 dialect: the dialect used to parse the input expressions. 1143 copy: if `False`, modify this expression instance in-place. 1144 opts: other options to use to parse the input expressions. 1145 1146 Returns: 1147 Delete: the modified expression. 1148 """ 1149 return _apply_conjunction_builder( 1150 *expressions, 1151 instance=self, 1152 arg="where", 1153 append=append, 1154 into=Where, 1155 dialect=dialect, 1156 copy=copy, 1157 **opts, 1158 )
Append to or set the WHERE expressions.
Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql() "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append: if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
1160 def returning( 1161 self, 1162 expression: ExpOrStr, 1163 dialect: DialectType = None, 1164 copy: bool = True, 1165 **opts, 1166 ) -> Delete: 1167 """ 1168 Set the RETURNING expression. Not supported by all dialects. 1169 1170 Example: 1171 >>> delete("tbl").returning("*", dialect="postgres").sql() 1172 'DELETE FROM tbl RETURNING *' 1173 1174 Args: 1175 expression: the SQL code strings to parse. 1176 If an `Expression` instance is passed, it will be used as-is. 1177 dialect: the dialect used to parse the input expressions. 1178 copy: if `False`, modify this expression instance in-place. 1179 opts: other options to use to parse the input expressions. 1180 1181 Returns: 1182 Delete: the modified expression. 1183 """ 1184 return _apply_builder( 1185 expression=expression, 1186 instance=self, 1187 arg="returning", 1188 prefix="RETURNING", 1189 dialect=dialect, 1190 copy=copy, 1191 into=Returning, 1192 **opts, 1193 )
Set the RETURNING expression. Not supported by all dialects.
Example:
>>> delete("tbl").returning("*", dialect="postgres").sql() 'DELETE FROM tbl RETURNING *'
Arguments:
- expression: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Delete: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1196class Drop(Expression): 1197 arg_types = { 1198 "this": False, 1199 "kind": False, 1200 "exists": False, 1201 "temporary": False, 1202 "materialized": False, 1203 "cascade": False, 1204 "constraints": False, 1205 "purge": False, 1206 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1217class Directory(Expression): 1218 # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html 1219 arg_types = {"this": True, "local": False, "row_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1222class ForeignKey(Expression): 1223 arg_types = { 1224 "expressions": True, 1225 "reference": False, 1226 "delete": False, 1227 "update": False, 1228 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1261class Identifier(Expression): 1262 arg_types = {"this": True, "quoted": False} 1263 1264 @property 1265 def quoted(self): 1266 return bool(self.args.get("quoted")) 1267 1268 @property 1269 def hashable_args(self) -> t.Any: 1270 if self.quoted and any(char.isupper() for char in self.this): 1271 return (self.this, self.quoted) 1272 return self.this.lower() 1273 1274 @property 1275 def output_name(self): 1276 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1279class Index(Expression): 1280 arg_types = { 1281 "this": False, 1282 "table": False, 1283 "where": False, 1284 "columns": False, 1285 "unique": False, 1286 "primary": False, 1287 "amp": False, # teradata 1288 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1291class Insert(Expression): 1292 arg_types = { 1293 "with": False, 1294 "this": True, 1295 "expression": False, 1296 "returning": False, 1297 "overwrite": False, 1298 "exists": False, 1299 "partition": False, 1300 "alternative": False, 1301 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1318class LoadData(Expression): 1319 arg_types = { 1320 "this": True, 1321 "local": False, 1322 "overwrite": False, 1323 "inpath": True, 1324 "partition": False, 1325 "input_format": False, 1326 "serde": False, 1327 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1334class Fetch(Expression): 1335 arg_types = { 1336 "direction": False, 1337 "count": False, 1338 "percent": False, 1339 "with_ties": False, 1340 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1343class Group(Expression): 1344 arg_types = { 1345 "expressions": False, 1346 "grouping_sets": False, 1347 "cube": False, 1348 "rollup": False, 1349 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1360class Literal(Condition): 1361 arg_types = {"this": True, "is_string": True} 1362 1363 @property 1364 def hashable_args(self) -> t.Any: 1365 return (self.this, self.args.get("is_string")) 1366 1367 @classmethod 1368 def number(cls, number) -> Literal: 1369 return cls(this=str(number), is_string=False) 1370 1371 @classmethod 1372 def string(cls, string) -> Literal: 1373 return cls(this=str(string), is_string=True) 1374 1375 @property 1376 def output_name(self): 1377 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1380class Join(Expression): 1381 arg_types = { 1382 "this": True, 1383 "on": False, 1384 "side": False, 1385 "kind": False, 1386 "using": False, 1387 "natural": False, 1388 "hint": False, 1389 } 1390 1391 @property 1392 def kind(self): 1393 return self.text("kind").upper() 1394 1395 @property 1396 def side(self): 1397 return self.text("side").upper() 1398 1399 @property 1400 def hint(self): 1401 return self.text("hint").upper() 1402 1403 @property 1404 def alias_or_name(self): 1405 return self.this.alias_or_name 1406 1407 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1408 """ 1409 Append to or set the ON expressions. 1410 1411 Example: 1412 >>> import sqlglot 1413 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1414 'JOIN x ON y = 1' 1415 1416 Args: 1417 *expressions (str | Expression): the SQL code strings to parse. 1418 If an `Expression` instance is passed, it will be used as-is. 1419 Multiple expressions are combined with an AND operator. 1420 append (bool): if `True`, AND the new expressions to any existing expression. 1421 Otherwise, this resets the expression. 1422 dialect (str): the dialect used to parse the input expressions. 1423 copy (bool): if `False`, modify this expression instance in-place. 1424 opts (kwargs): other options to use to parse the input expressions. 1425 1426 Returns: 1427 Join: the modified join expression. 1428 """ 1429 join = _apply_conjunction_builder( 1430 *expressions, 1431 instance=self, 1432 arg="on", 1433 append=append, 1434 dialect=dialect, 1435 copy=copy, 1436 **opts, 1437 ) 1438 1439 if join.kind == "CROSS": 1440 join.set("kind", None) 1441 1442 return join 1443 1444 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1445 """ 1446 Append to or set the USING expressions. 1447 1448 Example: 1449 >>> import sqlglot 1450 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1451 'JOIN x USING (foo, bla)' 1452 1453 Args: 1454 *expressions (str | Expression): the SQL code strings to parse. 1455 If an `Expression` instance is passed, it will be used as-is. 1456 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1457 Otherwise, this resets the expression. 1458 dialect (str): the dialect used to parse the input expressions. 1459 copy (bool): if `False`, modify this expression instance in-place. 1460 opts (kwargs): other options to use to parse the input expressions. 1461 1462 Returns: 1463 Join: the modified join expression. 1464 """ 1465 join = _apply_list_builder( 1466 *expressions, 1467 instance=self, 1468 arg="using", 1469 append=append, 1470 dialect=dialect, 1471 copy=copy, 1472 **opts, 1473 ) 1474 1475 if join.kind == "CROSS": 1476 join.set("kind", None) 1477 1478 return join
1407 def on(self, *expressions, append=True, dialect=None, copy=True, **opts): 1408 """ 1409 Append to or set the ON expressions. 1410 1411 Example: 1412 >>> import sqlglot 1413 >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 1414 'JOIN x ON y = 1' 1415 1416 Args: 1417 *expressions (str | Expression): the SQL code strings to parse. 1418 If an `Expression` instance is passed, it will be used as-is. 1419 Multiple expressions are combined with an AND operator. 1420 append (bool): if `True`, AND the new expressions to any existing expression. 1421 Otherwise, this resets the expression. 1422 dialect (str): the dialect used to parse the input expressions. 1423 copy (bool): if `False`, modify this expression instance in-place. 1424 opts (kwargs): other options to use to parse the input expressions. 1425 1426 Returns: 1427 Join: the modified join expression. 1428 """ 1429 join = _apply_conjunction_builder( 1430 *expressions, 1431 instance=self, 1432 arg="on", 1433 append=append, 1434 dialect=dialect, 1435 copy=copy, 1436 **opts, 1437 ) 1438 1439 if join.kind == "CROSS": 1440 join.set("kind", None) 1441 1442 return join
Append to or set the ON expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql() 'JOIN x ON y = 1'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
1444 def using(self, *expressions, append=True, dialect=None, copy=True, **opts): 1445 """ 1446 Append to or set the USING expressions. 1447 1448 Example: 1449 >>> import sqlglot 1450 >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 1451 'JOIN x USING (foo, bla)' 1452 1453 Args: 1454 *expressions (str | Expression): the SQL code strings to parse. 1455 If an `Expression` instance is passed, it will be used as-is. 1456 append (bool): if `True`, concatenate the new expressions to the existing "using" list. 1457 Otherwise, this resets the expression. 1458 dialect (str): the dialect used to parse the input expressions. 1459 copy (bool): if `False`, modify this expression instance in-place. 1460 opts (kwargs): other options to use to parse the input expressions. 1461 1462 Returns: 1463 Join: the modified join expression. 1464 """ 1465 join = _apply_list_builder( 1466 *expressions, 1467 instance=self, 1468 arg="using", 1469 append=append, 1470 dialect=dialect, 1471 copy=copy, 1472 **opts, 1473 ) 1474 1475 if join.kind == "CROSS": 1476 join.set("kind", None) 1477 1478 return join
Append to or set the USING expressions.
Example:
>>> import sqlglot >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql() 'JOIN x USING (foo, bla)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Join: the modified join expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1481class Lateral(UDTF): 1482 arg_types = {"this": True, "view": False, "outer": False, "alias": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1485class MatchRecognize(Expression): 1486 arg_types = { 1487 "partition_by": False, 1488 "order": False, 1489 "measures": False, 1490 "rows": False, 1491 "after": False, 1492 "pattern": False, 1493 "define": False, 1494 "alias": False, 1495 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1534class AfterJournalProperty(Property): 1535 arg_types = {"no": True, "dual": False, "local": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1546class BlockCompressionProperty(Property): 1547 arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1562class DataBlocksizeProperty(Property): 1563 arg_types = {"size": False, "units": False, "min": False, "default": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1602class InputOutputFormat(Expression): 1603 arg_types = {"input_format": False, "output_format": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1606class IsolatedLoadingProperty(Property): 1607 arg_types = { 1608 "no": True, 1609 "concurrent": True, 1610 "for_all": True, 1611 "for_insert": True, 1612 "for_none": True, 1613 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1632class LockingProperty(Property): 1633 arg_types = { 1634 "this": False, 1635 "kind": True, 1636 "for_or_in": True, 1637 "lock_type": True, 1638 "override": False, 1639 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1650class MergeBlockRatioProperty(Property): 1651 arg_types = {"this": False, "no": False, "default": False, "percent": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1666class ReturnsProperty(Property): 1667 arg_types = {"this": True, "is_table": False, "table": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1674class RowFormatDelimitedProperty(Property): 1675 # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml 1676 arg_types = { 1677 "fields": False, 1678 "escaped": False, 1679 "collection_items": False, 1680 "map_keys": False, 1681 "lines": False, 1682 "null": False, 1683 "serde": False, 1684 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1739class Properties(Expression): 1740 arg_types = {"expressions": True} 1741 1742 NAME_TO_PROPERTY = { 1743 "ALGORITHM": AlgorithmProperty, 1744 "AUTO_INCREMENT": AutoIncrementProperty, 1745 "CHARACTER SET": CharacterSetProperty, 1746 "COLLATE": CollateProperty, 1747 "COMMENT": SchemaCommentProperty, 1748 "DEFINER": DefinerProperty, 1749 "DISTKEY": DistKeyProperty, 1750 "DISTSTYLE": DistStyleProperty, 1751 "ENGINE": EngineProperty, 1752 "EXECUTE AS": ExecuteAsProperty, 1753 "FORMAT": FileFormatProperty, 1754 "LANGUAGE": LanguageProperty, 1755 "LOCATION": LocationProperty, 1756 "PARTITIONED_BY": PartitionedByProperty, 1757 "RETURNS": ReturnsProperty, 1758 "ROW_FORMAT": RowFormatProperty, 1759 "SORTKEY": SortKeyProperty, 1760 "TABLE_FORMAT": TableFormatProperty, 1761 } 1762 1763 PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()} 1764 1765 # CREATE property locations 1766 # Form: schema specified 1767 # create [POST_CREATE] 1768 # table a [POST_NAME] 1769 # (b int) [POST_SCHEMA] 1770 # with ([POST_WITH]) 1771 # index (b) [POST_INDEX] 1772 # 1773 # Form: alias selection 1774 # create [POST_CREATE] 1775 # table a [POST_NAME] 1776 # as [POST_ALIAS] (select * from b) [POST_EXPRESSION] 1777 # index (c) [POST_INDEX] 1778 class Location(AutoName): 1779 POST_CREATE = auto() 1780 POST_NAME = auto() 1781 POST_SCHEMA = auto() 1782 POST_WITH = auto() 1783 POST_ALIAS = auto() 1784 POST_EXPRESSION = auto() 1785 POST_INDEX = auto() 1786 UNSUPPORTED = auto() 1787 1788 @classmethod 1789 def from_dict(cls, properties_dict) -> Properties: 1790 expressions = [] 1791 for key, value in properties_dict.items(): 1792 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1793 if property_cls: 1794 expressions.append(property_cls(this=convert(value))) 1795 else: 1796 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1797 1798 return cls(expressions=expressions)
1788 @classmethod 1789 def from_dict(cls, properties_dict) -> Properties: 1790 expressions = [] 1791 for key, value in properties_dict.items(): 1792 property_cls = cls.NAME_TO_PROPERTY.get(key.upper()) 1793 if property_cls: 1794 expressions.append(property_cls(this=convert(value))) 1795 else: 1796 expressions.append(Property(this=Literal.string(key), value=convert(value))) 1797 1798 return cls(expressions=expressions)
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1778 class Location(AutoName): 1779 POST_CREATE = auto() 1780 POST_NAME = auto() 1781 POST_SCHEMA = auto() 1782 POST_WITH = auto() 1783 POST_ALIAS = auto() 1784 POST_EXPRESSION = auto() 1785 POST_INDEX = auto() 1786 UNSUPPORTED = auto()
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1810class Reference(Expression): 1811 arg_types = {"this": True, "expressions": False, "options": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1818class Subqueryable(Unionable): 1819 def subquery(self, alias=None, copy=True) -> Subquery: 1820 """ 1821 Convert this expression to an aliased expression that can be used as a Subquery. 1822 1823 Example: 1824 >>> subquery = Select().select("x").from_("tbl").subquery() 1825 >>> Select().select("x").from_(subquery).sql() 1826 'SELECT x FROM (SELECT x FROM tbl)' 1827 1828 Args: 1829 alias (str | Identifier): an optional alias for the subquery 1830 copy (bool): if `False`, modify this expression instance in-place. 1831 1832 Returns: 1833 Alias: the subquery 1834 """ 1835 instance = _maybe_copy(self, copy) 1836 return Subquery( 1837 this=instance, 1838 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1839 ) 1840 1841 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1842 raise NotImplementedError 1843 1844 @property 1845 def ctes(self): 1846 with_ = self.args.get("with") 1847 if not with_: 1848 return [] 1849 return with_.expressions 1850 1851 @property 1852 def selects(self): 1853 raise NotImplementedError("Subqueryable objects must implement `selects`") 1854 1855 @property 1856 def named_selects(self): 1857 raise NotImplementedError("Subqueryable objects must implement `named_selects`") 1858 1859 def with_( 1860 self, 1861 alias, 1862 as_, 1863 recursive=None, 1864 append=True, 1865 dialect=None, 1866 copy=True, 1867 **opts, 1868 ): 1869 """ 1870 Append to or set the common table expressions. 1871 1872 Example: 1873 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1874 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1875 1876 Args: 1877 alias (str | Expression): the SQL code string to parse as the table name. 1878 If an `Expression` instance is passed, this is used as-is. 1879 as_ (str | Expression): the SQL code string to parse as the table expression. 1880 If an `Expression` instance is passed, it will be used as-is. 1881 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1882 append (bool): if `True`, add to any existing expressions. 1883 Otherwise, this resets the expressions. 1884 dialect (str): the dialect used to parse the input expression. 1885 copy (bool): if `False`, modify this expression instance in-place. 1886 opts (kwargs): other options to use to parse the input expressions. 1887 1888 Returns: 1889 Select: the modified expression. 1890 """ 1891 alias_expression = maybe_parse( 1892 alias, 1893 dialect=dialect, 1894 into=TableAlias, 1895 **opts, 1896 ) 1897 as_expression = maybe_parse( 1898 as_, 1899 dialect=dialect, 1900 **opts, 1901 ) 1902 cte = CTE( 1903 this=as_expression, 1904 alias=alias_expression, 1905 ) 1906 return _apply_child_list_builder( 1907 cte, 1908 instance=self, 1909 arg="with", 1910 append=append, 1911 copy=copy, 1912 into=With, 1913 properties={"recursive": recursive or False}, 1914 )
1819 def subquery(self, alias=None, copy=True) -> Subquery: 1820 """ 1821 Convert this expression to an aliased expression that can be used as a Subquery. 1822 1823 Example: 1824 >>> subquery = Select().select("x").from_("tbl").subquery() 1825 >>> Select().select("x").from_(subquery).sql() 1826 'SELECT x FROM (SELECT x FROM tbl)' 1827 1828 Args: 1829 alias (str | Identifier): an optional alias for the subquery 1830 copy (bool): if `False`, modify this expression instance in-place. 1831 1832 Returns: 1833 Alias: the subquery 1834 """ 1835 instance = _maybe_copy(self, copy) 1836 return Subquery( 1837 this=instance, 1838 alias=TableAlias(this=to_identifier(alias)) if alias else None, 1839 )
Convert this expression to an aliased expression that can be used as a Subquery.
Example:
>>> subquery = Select().select("x").from_("tbl").subquery() >>> Select().select("x").from_(subquery).sql() 'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
- alias (str | Identifier): an optional alias for the subquery
- copy (bool): if
False, modify this expression instance in-place.
Returns:
Alias: the subquery
1859 def with_( 1860 self, 1861 alias, 1862 as_, 1863 recursive=None, 1864 append=True, 1865 dialect=None, 1866 copy=True, 1867 **opts, 1868 ): 1869 """ 1870 Append to or set the common table expressions. 1871 1872 Example: 1873 >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 1874 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2' 1875 1876 Args: 1877 alias (str | Expression): the SQL code string to parse as the table name. 1878 If an `Expression` instance is passed, this is used as-is. 1879 as_ (str | Expression): the SQL code string to parse as the table expression. 1880 If an `Expression` instance is passed, it will be used as-is. 1881 recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`. 1882 append (bool): if `True`, add to any existing expressions. 1883 Otherwise, this resets the expressions. 1884 dialect (str): the dialect used to parse the input expression. 1885 copy (bool): if `False`, modify this expression instance in-place. 1886 opts (kwargs): other options to use to parse the input expressions. 1887 1888 Returns: 1889 Select: the modified expression. 1890 """ 1891 alias_expression = maybe_parse( 1892 alias, 1893 dialect=dialect, 1894 into=TableAlias, 1895 **opts, 1896 ) 1897 as_expression = maybe_parse( 1898 as_, 1899 dialect=dialect, 1900 **opts, 1901 ) 1902 cte = CTE( 1903 this=as_expression, 1904 alias=alias_expression, 1905 ) 1906 return _apply_child_list_builder( 1907 cte, 1908 instance=self, 1909 arg="with", 1910 append=append, 1911 copy=copy, 1912 into=With, 1913 properties={"recursive": recursive or False}, 1914 )
Append to or set the common table expressions.
Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql() 'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
- alias (str | Expression): the SQL code string to parse as the table name.
If an
Expressioninstance is passed, this is used as-is. - as_ (str | Expression): the SQL code string to parse as the table expression.
If an
Expressioninstance is passed, it will be used as-is. - recursive (bool): set the RECURSIVE part of the expression. Defaults to
False. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1938class Table(Expression): 1939 arg_types = { 1940 "this": True, 1941 "alias": False, 1942 "db": False, 1943 "catalog": False, 1944 "laterals": False, 1945 "joins": False, 1946 "pivots": False, 1947 "hints": False, 1948 "system_time": False, 1949 } 1950 1951 @property 1952 def db(self) -> str: 1953 return self.text("db") 1954 1955 @property 1956 def catalog(self) -> str: 1957 return self.text("catalog")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1961class SystemTime(Expression): 1962 arg_types = { 1963 "this": False, 1964 "expression": False, 1965 "kind": True, 1966 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
1969class Union(Subqueryable): 1970 arg_types = { 1971 "with": False, 1972 "this": True, 1973 "expression": True, 1974 "distinct": False, 1975 **QUERY_MODIFIERS, 1976 } 1977 1978 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1979 """ 1980 Set the LIMIT expression. 1981 1982 Example: 1983 >>> select("1").union(select("1")).limit(1).sql() 1984 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1985 1986 Args: 1987 expression (str | int | Expression): the SQL code string to parse. 1988 This can also be an integer. 1989 If a `Limit` instance is passed, this is used as-is. 1990 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1991 dialect (str): the dialect used to parse the input expression. 1992 copy (bool): if `False`, modify this expression instance in-place. 1993 opts (kwargs): other options to use to parse the input expressions. 1994 1995 Returns: 1996 Select: The limited subqueryable. 1997 """ 1998 return ( 1999 select("*") 2000 .from_(self.subquery(alias="_l_0", copy=copy)) 2001 .limit(expression, dialect=dialect, copy=False, **opts) 2002 ) 2003 2004 def select( 2005 self, 2006 *expressions: ExpOrStr, 2007 append: bool = True, 2008 dialect: DialectType = None, 2009 copy: bool = True, 2010 **opts, 2011 ) -> Union: 2012 """Append to or set the SELECT of the union recursively. 2013 2014 Example: 2015 >>> from sqlglot import parse_one 2016 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2017 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2018 2019 Args: 2020 *expressions: the SQL code strings to parse. 2021 If an `Expression` instance is passed, it will be used as-is. 2022 append: if `True`, add to any existing expressions. 2023 Otherwise, this resets the expressions. 2024 dialect: the dialect used to parse the input expressions. 2025 copy: if `False`, modify this expression instance in-place. 2026 opts: other options to use to parse the input expressions. 2027 2028 Returns: 2029 Union: the modified expression. 2030 """ 2031 this = self.copy() if copy else self 2032 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2033 this.expression.unnest().select( 2034 *expressions, append=append, dialect=dialect, copy=False, **opts 2035 ) 2036 return this 2037 2038 @property 2039 def named_selects(self): 2040 return self.this.unnest().named_selects 2041 2042 @property 2043 def is_star(self) -> bool: 2044 return self.this.is_star or self.expression.is_star 2045 2046 @property 2047 def selects(self): 2048 return self.this.unnest().selects 2049 2050 @property 2051 def left(self): 2052 return self.this 2053 2054 @property 2055 def right(self): 2056 return self.expression
1978 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 1979 """ 1980 Set the LIMIT expression. 1981 1982 Example: 1983 >>> select("1").union(select("1")).limit(1).sql() 1984 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1' 1985 1986 Args: 1987 expression (str | int | Expression): the SQL code string to parse. 1988 This can also be an integer. 1989 If a `Limit` instance is passed, this is used as-is. 1990 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 1991 dialect (str): the dialect used to parse the input expression. 1992 copy (bool): if `False`, modify this expression instance in-place. 1993 opts (kwargs): other options to use to parse the input expressions. 1994 1995 Returns: 1996 Select: The limited subqueryable. 1997 """ 1998 return ( 1999 select("*") 2000 .from_(self.subquery(alias="_l_0", copy=copy)) 2001 .limit(expression, dialect=dialect, copy=False, **opts) 2002 )
Set the LIMIT expression.
Example:
>>> select("1").union(select("1")).limit(1).sql() 'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limitinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aLimit. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: The limited subqueryable.
2004 def select( 2005 self, 2006 *expressions: ExpOrStr, 2007 append: bool = True, 2008 dialect: DialectType = None, 2009 copy: bool = True, 2010 **opts, 2011 ) -> Union: 2012 """Append to or set the SELECT of the union recursively. 2013 2014 Example: 2015 >>> from sqlglot import parse_one 2016 >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 2017 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z' 2018 2019 Args: 2020 *expressions: the SQL code strings to parse. 2021 If an `Expression` instance is passed, it will be used as-is. 2022 append: if `True`, add to any existing expressions. 2023 Otherwise, this resets the expressions. 2024 dialect: the dialect used to parse the input expressions. 2025 copy: if `False`, modify this expression instance in-place. 2026 opts: other options to use to parse the input expressions. 2027 2028 Returns: 2029 Union: the modified expression. 2030 """ 2031 this = self.copy() if copy else self 2032 this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts) 2033 this.expression.unnest().select( 2034 *expressions, append=append, dialect=dialect, copy=False, **opts 2035 ) 2036 return this
Append to or set the SELECT of the union recursively.
Example:
>>> from sqlglot import parse_one >>> parse_one("select a from x union select a from y union select a from z").select("b").sql() 'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append: if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Union: the modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2067class Unnest(UDTF): 2068 arg_types = { 2069 "expressions": True, 2070 "ordinality": False, 2071 "alias": False, 2072 "offset": False, 2073 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2076class Update(Expression): 2077 arg_types = { 2078 "with": False, 2079 "this": False, 2080 "expressions": True, 2081 "from": False, 2082 "where": False, 2083 "returning": False, 2084 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2087class Values(UDTF): 2088 arg_types = { 2089 "expressions": True, 2090 "ordinality": False, 2091 "alias": False, 2092 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2109class Select(Subqueryable): 2110 arg_types = { 2111 "with": False, 2112 "kind": False, 2113 "expressions": False, 2114 "hint": False, 2115 "distinct": False, 2116 "into": False, 2117 "from": False, 2118 **QUERY_MODIFIERS, 2119 } 2120 2121 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2122 """ 2123 Set the FROM expression. 2124 2125 Example: 2126 >>> Select().from_("tbl").select("x").sql() 2127 'SELECT x FROM tbl' 2128 2129 Args: 2130 *expressions (str | Expression): the SQL code strings to parse. 2131 If a `From` instance is passed, this is used as-is. 2132 If another `Expression` instance is passed, it will be wrapped in a `From`. 2133 append (bool): if `True`, add to any existing expressions. 2134 Otherwise, this flattens all the `From` expression into a single expression. 2135 dialect (str): the dialect used to parse the input expression. 2136 copy (bool): if `False`, modify this expression instance in-place. 2137 opts (kwargs): other options to use to parse the input expressions. 2138 2139 Returns: 2140 Select: the modified expression. 2141 """ 2142 return _apply_child_list_builder( 2143 *expressions, 2144 instance=self, 2145 arg="from", 2146 append=append, 2147 copy=copy, 2148 prefix="FROM", 2149 into=From, 2150 dialect=dialect, 2151 **opts, 2152 ) 2153 2154 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2155 """ 2156 Set the GROUP BY expression. 2157 2158 Example: 2159 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2160 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2161 2162 Args: 2163 *expressions (str | Expression): the SQL code strings to parse. 2164 If a `Group` instance is passed, this is used as-is. 2165 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2166 If nothing is passed in then a group by is not applied to the expression 2167 append (bool): if `True`, add to any existing expressions. 2168 Otherwise, this flattens all the `Group` expression into a single expression. 2169 dialect (str): the dialect used to parse the input expression. 2170 copy (bool): if `False`, modify this expression instance in-place. 2171 opts (kwargs): other options to use to parse the input expressions. 2172 2173 Returns: 2174 Select: the modified expression. 2175 """ 2176 if not expressions: 2177 return self if not copy else self.copy() 2178 return _apply_child_list_builder( 2179 *expressions, 2180 instance=self, 2181 arg="group", 2182 append=append, 2183 copy=copy, 2184 prefix="GROUP BY", 2185 into=Group, 2186 dialect=dialect, 2187 **opts, 2188 ) 2189 2190 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2191 """ 2192 Set the ORDER BY expression. 2193 2194 Example: 2195 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2196 'SELECT x FROM tbl ORDER BY x DESC' 2197 2198 Args: 2199 *expressions (str | Expression): the SQL code strings to parse. 2200 If a `Group` instance is passed, this is used as-is. 2201 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2202 append (bool): if `True`, add to any existing expressions. 2203 Otherwise, this flattens all the `Order` expression into a single expression. 2204 dialect (str): the dialect used to parse the input expression. 2205 copy (bool): if `False`, modify this expression instance in-place. 2206 opts (kwargs): other options to use to parse the input expressions. 2207 2208 Returns: 2209 Select: the modified expression. 2210 """ 2211 return _apply_child_list_builder( 2212 *expressions, 2213 instance=self, 2214 arg="order", 2215 append=append, 2216 copy=copy, 2217 prefix="ORDER BY", 2218 into=Order, 2219 dialect=dialect, 2220 **opts, 2221 ) 2222 2223 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2224 """ 2225 Set the SORT BY expression. 2226 2227 Example: 2228 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2229 'SELECT x FROM tbl SORT BY x DESC' 2230 2231 Args: 2232 *expressions (str | Expression): the SQL code strings to parse. 2233 If a `Group` instance is passed, this is used as-is. 2234 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2235 append (bool): if `True`, add to any existing expressions. 2236 Otherwise, this flattens all the `Order` expression into a single expression. 2237 dialect (str): the dialect used to parse the input expression. 2238 copy (bool): if `False`, modify this expression instance in-place. 2239 opts (kwargs): other options to use to parse the input expressions. 2240 2241 Returns: 2242 Select: the modified expression. 2243 """ 2244 return _apply_child_list_builder( 2245 *expressions, 2246 instance=self, 2247 arg="sort", 2248 append=append, 2249 copy=copy, 2250 prefix="SORT BY", 2251 into=Sort, 2252 dialect=dialect, 2253 **opts, 2254 ) 2255 2256 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2257 """ 2258 Set the CLUSTER BY expression. 2259 2260 Example: 2261 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2262 'SELECT x FROM tbl CLUSTER BY x DESC' 2263 2264 Args: 2265 *expressions (str | Expression): the SQL code strings to parse. 2266 If a `Group` instance is passed, this is used as-is. 2267 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2268 append (bool): if `True`, add to any existing expressions. 2269 Otherwise, this flattens all the `Order` expression into a single expression. 2270 dialect (str): the dialect used to parse the input expression. 2271 copy (bool): if `False`, modify this expression instance in-place. 2272 opts (kwargs): other options to use to parse the input expressions. 2273 2274 Returns: 2275 Select: the modified expression. 2276 """ 2277 return _apply_child_list_builder( 2278 *expressions, 2279 instance=self, 2280 arg="cluster", 2281 append=append, 2282 copy=copy, 2283 prefix="CLUSTER BY", 2284 into=Cluster, 2285 dialect=dialect, 2286 **opts, 2287 ) 2288 2289 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2290 """ 2291 Set the LIMIT expression. 2292 2293 Example: 2294 >>> Select().from_("tbl").select("x").limit(10).sql() 2295 'SELECT x FROM tbl LIMIT 10' 2296 2297 Args: 2298 expression (str | int | Expression): the SQL code string to parse. 2299 This can also be an integer. 2300 If a `Limit` instance is passed, this is used as-is. 2301 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2302 dialect (str): the dialect used to parse the input expression. 2303 copy (bool): if `False`, modify this expression instance in-place. 2304 opts (kwargs): other options to use to parse the input expressions. 2305 2306 Returns: 2307 Select: the modified expression. 2308 """ 2309 return _apply_builder( 2310 expression=expression, 2311 instance=self, 2312 arg="limit", 2313 into=Limit, 2314 prefix="LIMIT", 2315 dialect=dialect, 2316 copy=copy, 2317 **opts, 2318 ) 2319 2320 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2321 """ 2322 Set the OFFSET expression. 2323 2324 Example: 2325 >>> Select().from_("tbl").select("x").offset(10).sql() 2326 'SELECT x FROM tbl OFFSET 10' 2327 2328 Args: 2329 expression (str | int | Expression): the SQL code string to parse. 2330 This can also be an integer. 2331 If a `Offset` instance is passed, this is used as-is. 2332 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2333 dialect (str): the dialect used to parse the input expression. 2334 copy (bool): if `False`, modify this expression instance in-place. 2335 opts (kwargs): other options to use to parse the input expressions. 2336 2337 Returns: 2338 Select: the modified expression. 2339 """ 2340 return _apply_builder( 2341 expression=expression, 2342 instance=self, 2343 arg="offset", 2344 into=Offset, 2345 prefix="OFFSET", 2346 dialect=dialect, 2347 copy=copy, 2348 **opts, 2349 ) 2350 2351 def select( 2352 self, 2353 *expressions: ExpOrStr, 2354 append: bool = True, 2355 dialect: DialectType = None, 2356 copy: bool = True, 2357 **opts, 2358 ) -> Select: 2359 """ 2360 Append to or set the SELECT expressions. 2361 2362 Example: 2363 >>> Select().select("x", "y").sql() 2364 'SELECT x, y' 2365 2366 Args: 2367 *expressions: the SQL code strings to parse. 2368 If an `Expression` instance is passed, it will be used as-is. 2369 append: if `True`, add to any existing expressions. 2370 Otherwise, this resets the expressions. 2371 dialect: the dialect used to parse the input expressions. 2372 copy: if `False`, modify this expression instance in-place. 2373 opts: other options to use to parse the input expressions. 2374 2375 Returns: 2376 Select: the modified expression. 2377 """ 2378 return _apply_list_builder( 2379 *expressions, 2380 instance=self, 2381 arg="expressions", 2382 append=append, 2383 dialect=dialect, 2384 copy=copy, 2385 **opts, 2386 ) 2387 2388 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2389 """ 2390 Append to or set the LATERAL expressions. 2391 2392 Example: 2393 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2394 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2395 2396 Args: 2397 *expressions (str | Expression): the SQL code strings to parse. 2398 If an `Expression` instance is passed, it will be used as-is. 2399 append (bool): if `True`, add to any existing expressions. 2400 Otherwise, this resets the expressions. 2401 dialect (str): the dialect used to parse the input expressions. 2402 copy (bool): if `False`, modify this expression instance in-place. 2403 opts (kwargs): other options to use to parse the input expressions. 2404 2405 Returns: 2406 Select: the modified expression. 2407 """ 2408 return _apply_list_builder( 2409 *expressions, 2410 instance=self, 2411 arg="laterals", 2412 append=append, 2413 into=Lateral, 2414 prefix="LATERAL VIEW", 2415 dialect=dialect, 2416 copy=copy, 2417 **opts, 2418 ) 2419 2420 def join( 2421 self, 2422 expression, 2423 on=None, 2424 using=None, 2425 append=True, 2426 join_type=None, 2427 join_alias=None, 2428 dialect=None, 2429 copy=True, 2430 **opts, 2431 ) -> Select: 2432 """ 2433 Append to or set the JOIN expressions. 2434 2435 Example: 2436 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2437 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2438 2439 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2440 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2441 2442 Use `join_type` to change the type of join: 2443 2444 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2445 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2446 2447 Args: 2448 expression (str | Expression): the SQL code string to parse. 2449 If an `Expression` instance is passed, it will be used as-is. 2450 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2451 If an `Expression` instance is passed, it will be used as-is. 2452 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2453 If an `Expression` instance is passed, it will be used as-is. 2454 append (bool): if `True`, add to any existing expressions. 2455 Otherwise, this resets the expressions. 2456 join_type (str): If set, alter the parsed join type 2457 dialect (str): the dialect used to parse the input expressions. 2458 copy (bool): if `False`, modify this expression instance in-place. 2459 opts (kwargs): other options to use to parse the input expressions. 2460 2461 Returns: 2462 Select: the modified expression. 2463 """ 2464 parse_args = {"dialect": dialect, **opts} 2465 2466 try: 2467 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2468 except ParseError: 2469 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2470 2471 join = expression if isinstance(expression, Join) else Join(this=expression) 2472 2473 if isinstance(join.this, Select): 2474 join.this.replace(join.this.subquery()) 2475 2476 if join_type: 2477 natural: t.Optional[Token] 2478 side: t.Optional[Token] 2479 kind: t.Optional[Token] 2480 2481 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2482 2483 if natural: 2484 join.set("natural", True) 2485 if side: 2486 join.set("side", side.text) 2487 if kind: 2488 join.set("kind", kind.text) 2489 2490 if on: 2491 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2492 join.set("on", on) 2493 2494 if using: 2495 join = _apply_list_builder( 2496 *ensure_collection(using), 2497 instance=join, 2498 arg="using", 2499 append=append, 2500 copy=copy, 2501 **opts, 2502 ) 2503 2504 if join_alias: 2505 join.set("this", alias_(join.this, join_alias, table=True)) 2506 return _apply_list_builder( 2507 join, 2508 instance=self, 2509 arg="joins", 2510 append=append, 2511 copy=copy, 2512 **opts, 2513 ) 2514 2515 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2516 """ 2517 Append to or set the WHERE expressions. 2518 2519 Example: 2520 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2521 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2522 2523 Args: 2524 *expressions (str | Expression): the SQL code strings to parse. 2525 If an `Expression` instance is passed, it will be used as-is. 2526 Multiple expressions are combined with an AND operator. 2527 append (bool): if `True`, AND the new expressions to any existing expression. 2528 Otherwise, this resets the expression. 2529 dialect (str): the dialect used to parse the input expressions. 2530 copy (bool): if `False`, modify this expression instance in-place. 2531 opts (kwargs): other options to use to parse the input expressions. 2532 2533 Returns: 2534 Select: the modified expression. 2535 """ 2536 return _apply_conjunction_builder( 2537 *expressions, 2538 instance=self, 2539 arg="where", 2540 append=append, 2541 into=Where, 2542 dialect=dialect, 2543 copy=copy, 2544 **opts, 2545 ) 2546 2547 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2548 """ 2549 Append to or set the HAVING expressions. 2550 2551 Example: 2552 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2553 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2554 2555 Args: 2556 *expressions (str | Expression): the SQL code strings to parse. 2557 If an `Expression` instance is passed, it will be used as-is. 2558 Multiple expressions are combined with an AND operator. 2559 append (bool): if `True`, AND the new expressions to any existing expression. 2560 Otherwise, this resets the expression. 2561 dialect (str): the dialect used to parse the input expressions. 2562 copy (bool): if `False`, modify this expression instance in-place. 2563 opts (kwargs): other options to use to parse the input expressions. 2564 2565 Returns: 2566 Select: the modified expression. 2567 """ 2568 return _apply_conjunction_builder( 2569 *expressions, 2570 instance=self, 2571 arg="having", 2572 append=append, 2573 into=Having, 2574 dialect=dialect, 2575 copy=copy, 2576 **opts, 2577 ) 2578 2579 def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2580 return _apply_list_builder( 2581 *expressions, 2582 instance=self, 2583 arg="windows", 2584 append=append, 2585 into=Window, 2586 dialect=dialect, 2587 copy=copy, 2588 **opts, 2589 ) 2590 2591 def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2592 return _apply_conjunction_builder( 2593 *expressions, 2594 instance=self, 2595 arg="qualify", 2596 append=append, 2597 into=Qualify, 2598 dialect=dialect, 2599 copy=copy, 2600 **opts, 2601 ) 2602 2603 def distinct(self, distinct=True, copy=True) -> Select: 2604 """ 2605 Set the OFFSET expression. 2606 2607 Example: 2608 >>> Select().from_("tbl").select("x").distinct().sql() 2609 'SELECT DISTINCT x FROM tbl' 2610 2611 Args: 2612 distinct (bool): whether the Select should be distinct 2613 copy (bool): if `False`, modify this expression instance in-place. 2614 2615 Returns: 2616 Select: the modified expression. 2617 """ 2618 instance = _maybe_copy(self, copy) 2619 instance.set("distinct", Distinct() if distinct else None) 2620 return instance 2621 2622 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2623 """ 2624 Convert this expression to a CREATE TABLE AS statement. 2625 2626 Example: 2627 >>> Select().select("*").from_("tbl").ctas("x").sql() 2628 'CREATE TABLE x AS SELECT * FROM tbl' 2629 2630 Args: 2631 table (str | Expression): the SQL code string to parse as the table name. 2632 If another `Expression` instance is passed, it will be used as-is. 2633 properties (dict): an optional mapping of table properties 2634 dialect (str): the dialect used to parse the input table. 2635 copy (bool): if `False`, modify this expression instance in-place. 2636 opts (kwargs): other options to use to parse the input table. 2637 2638 Returns: 2639 Create: the CREATE TABLE AS expression 2640 """ 2641 instance = _maybe_copy(self, copy) 2642 table_expression = maybe_parse( 2643 table, 2644 into=Table, 2645 dialect=dialect, 2646 **opts, 2647 ) 2648 properties_expression = None 2649 if properties: 2650 properties_expression = Properties.from_dict(properties) 2651 2652 return Create( 2653 this=table_expression, 2654 kind="table", 2655 expression=instance, 2656 properties=properties_expression, 2657 ) 2658 2659 def lock(self, update: bool = True, copy: bool = True) -> Select: 2660 """ 2661 Set the locking read mode for this expression. 2662 2663 Examples: 2664 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2665 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2666 2667 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2668 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2669 2670 Args: 2671 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2672 copy: if `False`, modify this expression instance in-place. 2673 2674 Returns: 2675 The modified expression. 2676 """ 2677 2678 inst = _maybe_copy(self, copy) 2679 inst.set("lock", Lock(update=update)) 2680 2681 return inst 2682 2683 @property 2684 def named_selects(self) -> t.List[str]: 2685 return [e.output_name for e in self.expressions if e.alias_or_name] 2686 2687 @property 2688 def is_star(self) -> bool: 2689 return any(expression.is_star for expression in self.expressions) 2690 2691 @property 2692 def selects(self) -> t.List[Expression]: 2693 return self.expressions
2121 def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2122 """ 2123 Set the FROM expression. 2124 2125 Example: 2126 >>> Select().from_("tbl").select("x").sql() 2127 'SELECT x FROM tbl' 2128 2129 Args: 2130 *expressions (str | Expression): the SQL code strings to parse. 2131 If a `From` instance is passed, this is used as-is. 2132 If another `Expression` instance is passed, it will be wrapped in a `From`. 2133 append (bool): if `True`, add to any existing expressions. 2134 Otherwise, this flattens all the `From` expression into a single expression. 2135 dialect (str): the dialect used to parse the input expression. 2136 copy (bool): if `False`, modify this expression instance in-place. 2137 opts (kwargs): other options to use to parse the input expressions. 2138 2139 Returns: 2140 Select: the modified expression. 2141 """ 2142 return _apply_child_list_builder( 2143 *expressions, 2144 instance=self, 2145 arg="from", 2146 append=append, 2147 copy=copy, 2148 prefix="FROM", 2149 into=From, 2150 dialect=dialect, 2151 **opts, 2152 )
Set the FROM expression.
Example:
>>> Select().from_("tbl").select("x").sql() 'SELECT x FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Frominstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aFrom. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theFromexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2154 def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2155 """ 2156 Set the GROUP BY expression. 2157 2158 Example: 2159 >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 2160 'SELECT x, COUNT(1) FROM tbl GROUP BY x' 2161 2162 Args: 2163 *expressions (str | Expression): the SQL code strings to parse. 2164 If a `Group` instance is passed, this is used as-is. 2165 If another `Expression` instance is passed, it will be wrapped in a `Group`. 2166 If nothing is passed in then a group by is not applied to the expression 2167 append (bool): if `True`, add to any existing expressions. 2168 Otherwise, this flattens all the `Group` expression into a single expression. 2169 dialect (str): the dialect used to parse the input expression. 2170 copy (bool): if `False`, modify this expression instance in-place. 2171 opts (kwargs): other options to use to parse the input expressions. 2172 2173 Returns: 2174 Select: the modified expression. 2175 """ 2176 if not expressions: 2177 return self if not copy else self.copy() 2178 return _apply_child_list_builder( 2179 *expressions, 2180 instance=self, 2181 arg="group", 2182 append=append, 2183 copy=copy, 2184 prefix="GROUP BY", 2185 into=Group, 2186 dialect=dialect, 2187 **opts, 2188 )
Set the GROUP BY expression.
Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql() 'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aGroup. If nothing is passed in then a group by is not applied to the expression - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theGroupexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2190 def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2191 """ 2192 Set the ORDER BY expression. 2193 2194 Example: 2195 >>> Select().from_("tbl").select("x").order_by("x DESC").sql() 2196 'SELECT x FROM tbl ORDER BY x DESC' 2197 2198 Args: 2199 *expressions (str | Expression): the SQL code strings to parse. 2200 If a `Group` instance is passed, this is used as-is. 2201 If another `Expression` instance is passed, it will be wrapped in a `Order`. 2202 append (bool): if `True`, add to any existing expressions. 2203 Otherwise, this flattens all the `Order` expression into a single expression. 2204 dialect (str): the dialect used to parse the input expression. 2205 copy (bool): if `False`, modify this expression instance in-place. 2206 opts (kwargs): other options to use to parse the input expressions. 2207 2208 Returns: 2209 Select: the modified expression. 2210 """ 2211 return _apply_child_list_builder( 2212 *expressions, 2213 instance=self, 2214 arg="order", 2215 append=append, 2216 copy=copy, 2217 prefix="ORDER BY", 2218 into=Order, 2219 dialect=dialect, 2220 **opts, 2221 )
Set the ORDER BY expression.
Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql() 'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aOrder. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2223 def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2224 """ 2225 Set the SORT BY expression. 2226 2227 Example: 2228 >>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 2229 'SELECT x FROM tbl SORT BY x DESC' 2230 2231 Args: 2232 *expressions (str | Expression): the SQL code strings to parse. 2233 If a `Group` instance is passed, this is used as-is. 2234 If another `Expression` instance is passed, it will be wrapped in a `SORT`. 2235 append (bool): if `True`, add to any existing expressions. 2236 Otherwise, this flattens all the `Order` expression into a single expression. 2237 dialect (str): the dialect used to parse the input expression. 2238 copy (bool): if `False`, modify this expression instance in-place. 2239 opts (kwargs): other options to use to parse the input expressions. 2240 2241 Returns: 2242 Select: the modified expression. 2243 """ 2244 return _apply_child_list_builder( 2245 *expressions, 2246 instance=self, 2247 arg="sort", 2248 append=append, 2249 copy=copy, 2250 prefix="SORT BY", 2251 into=Sort, 2252 dialect=dialect, 2253 **opts, 2254 )
Set the SORT BY expression.
Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql() 'SELECT x FROM tbl SORT BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aSORT. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2256 def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2257 """ 2258 Set the CLUSTER BY expression. 2259 2260 Example: 2261 >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 2262 'SELECT x FROM tbl CLUSTER BY x DESC' 2263 2264 Args: 2265 *expressions (str | Expression): the SQL code strings to parse. 2266 If a `Group` instance is passed, this is used as-is. 2267 If another `Expression` instance is passed, it will be wrapped in a `Cluster`. 2268 append (bool): if `True`, add to any existing expressions. 2269 Otherwise, this flattens all the `Order` expression into a single expression. 2270 dialect (str): the dialect used to parse the input expression. 2271 copy (bool): if `False`, modify this expression instance in-place. 2272 opts (kwargs): other options to use to parse the input expressions. 2273 2274 Returns: 2275 Select: the modified expression. 2276 """ 2277 return _apply_child_list_builder( 2278 *expressions, 2279 instance=self, 2280 arg="cluster", 2281 append=append, 2282 copy=copy, 2283 prefix="CLUSTER BY", 2284 into=Cluster, 2285 dialect=dialect, 2286 **opts, 2287 )
Set the CLUSTER BY expression.
Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql() 'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If a
Groupinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aCluster. - append (bool): if
True, add to any existing expressions. Otherwise, this flattens all theOrderexpression into a single expression. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2289 def limit(self, expression, dialect=None, copy=True, **opts) -> Select: 2290 """ 2291 Set the LIMIT expression. 2292 2293 Example: 2294 >>> Select().from_("tbl").select("x").limit(10).sql() 2295 'SELECT x FROM tbl LIMIT 10' 2296 2297 Args: 2298 expression (str | int | Expression): the SQL code string to parse. 2299 This can also be an integer. 2300 If a `Limit` instance is passed, this is used as-is. 2301 If another `Expression` instance is passed, it will be wrapped in a `Limit`. 2302 dialect (str): the dialect used to parse the input expression. 2303 copy (bool): if `False`, modify this expression instance in-place. 2304 opts (kwargs): other options to use to parse the input expressions. 2305 2306 Returns: 2307 Select: the modified expression. 2308 """ 2309 return _apply_builder( 2310 expression=expression, 2311 instance=self, 2312 arg="limit", 2313 into=Limit, 2314 prefix="LIMIT", 2315 dialect=dialect, 2316 copy=copy, 2317 **opts, 2318 )
Set the LIMIT expression.
Example:
>>> Select().from_("tbl").select("x").limit(10).sql() 'SELECT x FROM tbl LIMIT 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Limitinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aLimit. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2320 def offset(self, expression, dialect=None, copy=True, **opts) -> Select: 2321 """ 2322 Set the OFFSET expression. 2323 2324 Example: 2325 >>> Select().from_("tbl").select("x").offset(10).sql() 2326 'SELECT x FROM tbl OFFSET 10' 2327 2328 Args: 2329 expression (str | int | Expression): the SQL code string to parse. 2330 This can also be an integer. 2331 If a `Offset` instance is passed, this is used as-is. 2332 If another `Expression` instance is passed, it will be wrapped in a `Offset`. 2333 dialect (str): the dialect used to parse the input expression. 2334 copy (bool): if `False`, modify this expression instance in-place. 2335 opts (kwargs): other options to use to parse the input expressions. 2336 2337 Returns: 2338 Select: the modified expression. 2339 """ 2340 return _apply_builder( 2341 expression=expression, 2342 instance=self, 2343 arg="offset", 2344 into=Offset, 2345 prefix="OFFSET", 2346 dialect=dialect, 2347 copy=copy, 2348 **opts, 2349 )
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").offset(10).sql() 'SELECT x FROM tbl OFFSET 10'
Arguments:
- expression (str | int | Expression): the SQL code string to parse.
This can also be an integer.
If a
Offsetinstance is passed, this is used as-is. If anotherExpressioninstance is passed, it will be wrapped in aOffset. - dialect (str): the dialect used to parse the input expression.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2351 def select( 2352 self, 2353 *expressions: ExpOrStr, 2354 append: bool = True, 2355 dialect: DialectType = None, 2356 copy: bool = True, 2357 **opts, 2358 ) -> Select: 2359 """ 2360 Append to or set the SELECT expressions. 2361 2362 Example: 2363 >>> Select().select("x", "y").sql() 2364 'SELECT x, y' 2365 2366 Args: 2367 *expressions: the SQL code strings to parse. 2368 If an `Expression` instance is passed, it will be used as-is. 2369 append: if `True`, add to any existing expressions. 2370 Otherwise, this resets the expressions. 2371 dialect: the dialect used to parse the input expressions. 2372 copy: if `False`, modify this expression instance in-place. 2373 opts: other options to use to parse the input expressions. 2374 2375 Returns: 2376 Select: the modified expression. 2377 """ 2378 return _apply_list_builder( 2379 *expressions, 2380 instance=self, 2381 arg="expressions", 2382 append=append, 2383 dialect=dialect, 2384 copy=copy, 2385 **opts, 2386 )
Append to or set the SELECT expressions.
Example:
>>> Select().select("x", "y").sql() 'SELECT x, y'
Arguments:
- *expressions: the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append: if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect: the dialect used to parse the input expressions.
- copy: if
False, modify this expression instance in-place. - opts: other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2388 def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2389 """ 2390 Append to or set the LATERAL expressions. 2391 2392 Example: 2393 >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 2394 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z' 2395 2396 Args: 2397 *expressions (str | Expression): the SQL code strings to parse. 2398 If an `Expression` instance is passed, it will be used as-is. 2399 append (bool): if `True`, add to any existing expressions. 2400 Otherwise, this resets the expressions. 2401 dialect (str): the dialect used to parse the input expressions. 2402 copy (bool): if `False`, modify this expression instance in-place. 2403 opts (kwargs): other options to use to parse the input expressions. 2404 2405 Returns: 2406 Select: the modified expression. 2407 """ 2408 return _apply_list_builder( 2409 *expressions, 2410 instance=self, 2411 arg="laterals", 2412 append=append, 2413 into=Lateral, 2414 prefix="LATERAL VIEW", 2415 dialect=dialect, 2416 copy=copy, 2417 **opts, 2418 )
Append to or set the LATERAL expressions.
Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql() 'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2420 def join( 2421 self, 2422 expression, 2423 on=None, 2424 using=None, 2425 append=True, 2426 join_type=None, 2427 join_alias=None, 2428 dialect=None, 2429 copy=True, 2430 **opts, 2431 ) -> Select: 2432 """ 2433 Append to or set the JOIN expressions. 2434 2435 Example: 2436 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 2437 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y' 2438 2439 >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 2440 'SELECT 1 FROM a JOIN b USING (x, y, z)' 2441 2442 Use `join_type` to change the type of join: 2443 2444 >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 2445 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y' 2446 2447 Args: 2448 expression (str | Expression): the SQL code string to parse. 2449 If an `Expression` instance is passed, it will be used as-is. 2450 on (str | Expression): optionally specify the join "on" criteria as a SQL string. 2451 If an `Expression` instance is passed, it will be used as-is. 2452 using (str | Expression): optionally specify the join "using" criteria as a SQL string. 2453 If an `Expression` instance is passed, it will be used as-is. 2454 append (bool): if `True`, add to any existing expressions. 2455 Otherwise, this resets the expressions. 2456 join_type (str): If set, alter the parsed join type 2457 dialect (str): the dialect used to parse the input expressions. 2458 copy (bool): if `False`, modify this expression instance in-place. 2459 opts (kwargs): other options to use to parse the input expressions. 2460 2461 Returns: 2462 Select: the modified expression. 2463 """ 2464 parse_args = {"dialect": dialect, **opts} 2465 2466 try: 2467 expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args) 2468 except ParseError: 2469 expression = maybe_parse(expression, into=(Join, Expression), **parse_args) 2470 2471 join = expression if isinstance(expression, Join) else Join(this=expression) 2472 2473 if isinstance(join.this, Select): 2474 join.this.replace(join.this.subquery()) 2475 2476 if join_type: 2477 natural: t.Optional[Token] 2478 side: t.Optional[Token] 2479 kind: t.Optional[Token] 2480 2481 natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args) # type: ignore 2482 2483 if natural: 2484 join.set("natural", True) 2485 if side: 2486 join.set("side", side.text) 2487 if kind: 2488 join.set("kind", kind.text) 2489 2490 if on: 2491 on = and_(*ensure_collection(on), dialect=dialect, **opts) 2492 join.set("on", on) 2493 2494 if using: 2495 join = _apply_list_builder( 2496 *ensure_collection(using), 2497 instance=join, 2498 arg="using", 2499 append=append, 2500 copy=copy, 2501 **opts, 2502 ) 2503 2504 if join_alias: 2505 join.set("this", alias_(join.this, join_alias, table=True)) 2506 return _apply_list_builder( 2507 join, 2508 instance=self, 2509 arg="joins", 2510 append=append, 2511 copy=copy, 2512 **opts, 2513 )
Append to or set the JOIN expressions.
Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql() 'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql() 'SELECT 1 FROM a JOIN b USING (x, y, z)'Use
join_typeto change the type of join:>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql() 'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
- expression (str | Expression): the SQL code string to parse.
If an
Expressioninstance is passed, it will be used as-is. - on (str | Expression): optionally specify the join "on" criteria as a SQL string.
If an
Expressioninstance is passed, it will be used as-is. - using (str | Expression): optionally specify the join "using" criteria as a SQL string.
If an
Expressioninstance is passed, it will be used as-is. - append (bool): if
True, add to any existing expressions. Otherwise, this resets the expressions. - join_type (str): If set, alter the parsed join type
- dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2515 def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2516 """ 2517 Append to or set the WHERE expressions. 2518 2519 Example: 2520 >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() 2521 "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'" 2522 2523 Args: 2524 *expressions (str | Expression): the SQL code strings to parse. 2525 If an `Expression` instance is passed, it will be used as-is. 2526 Multiple expressions are combined with an AND operator. 2527 append (bool): if `True`, AND the new expressions to any existing expression. 2528 Otherwise, this resets the expression. 2529 dialect (str): the dialect used to parse the input expressions. 2530 copy (bool): if `False`, modify this expression instance in-place. 2531 opts (kwargs): other options to use to parse the input expressions. 2532 2533 Returns: 2534 Select: the modified expression. 2535 """ 2536 return _apply_conjunction_builder( 2537 *expressions, 2538 instance=self, 2539 arg="where", 2540 append=append, 2541 into=Where, 2542 dialect=dialect, 2543 copy=copy, 2544 **opts, 2545 )
Append to or set the WHERE expressions.
Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql() "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2547 def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select: 2548 """ 2549 Append to or set the HAVING expressions. 2550 2551 Example: 2552 >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 2553 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3' 2554 2555 Args: 2556 *expressions (str | Expression): the SQL code strings to parse. 2557 If an `Expression` instance is passed, it will be used as-is. 2558 Multiple expressions are combined with an AND operator. 2559 append (bool): if `True`, AND the new expressions to any existing expression. 2560 Otherwise, this resets the expression. 2561 dialect (str): the dialect used to parse the input expressions. 2562 copy (bool): if `False`, modify this expression instance in-place. 2563 opts (kwargs): other options to use to parse the input expressions. 2564 2565 Returns: 2566 Select: the modified expression. 2567 """ 2568 return _apply_conjunction_builder( 2569 *expressions, 2570 instance=self, 2571 arg="having", 2572 append=append, 2573 into=Having, 2574 dialect=dialect, 2575 copy=copy, 2576 **opts, 2577 )
Append to or set the HAVING expressions.
Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql() 'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse.
If an
Expressioninstance is passed, it will be used as-is. Multiple expressions are combined with an AND operator. - append (bool): if
True, AND the new expressions to any existing expression. Otherwise, this resets the expression. - dialect (str): the dialect used to parse the input expressions.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input expressions.
Returns:
Select: the modified expression.
2603 def distinct(self, distinct=True, copy=True) -> Select: 2604 """ 2605 Set the OFFSET expression. 2606 2607 Example: 2608 >>> Select().from_("tbl").select("x").distinct().sql() 2609 'SELECT DISTINCT x FROM tbl' 2610 2611 Args: 2612 distinct (bool): whether the Select should be distinct 2613 copy (bool): if `False`, modify this expression instance in-place. 2614 2615 Returns: 2616 Select: the modified expression. 2617 """ 2618 instance = _maybe_copy(self, copy) 2619 instance.set("distinct", Distinct() if distinct else None) 2620 return instance
Set the OFFSET expression.
Example:
>>> Select().from_("tbl").select("x").distinct().sql() 'SELECT DISTINCT x FROM tbl'
Arguments:
- distinct (bool): whether the Select should be distinct
- copy (bool): if
False, modify this expression instance in-place.
Returns:
Select: the modified expression.
2622 def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create: 2623 """ 2624 Convert this expression to a CREATE TABLE AS statement. 2625 2626 Example: 2627 >>> Select().select("*").from_("tbl").ctas("x").sql() 2628 'CREATE TABLE x AS SELECT * FROM tbl' 2629 2630 Args: 2631 table (str | Expression): the SQL code string to parse as the table name. 2632 If another `Expression` instance is passed, it will be used as-is. 2633 properties (dict): an optional mapping of table properties 2634 dialect (str): the dialect used to parse the input table. 2635 copy (bool): if `False`, modify this expression instance in-place. 2636 opts (kwargs): other options to use to parse the input table. 2637 2638 Returns: 2639 Create: the CREATE TABLE AS expression 2640 """ 2641 instance = _maybe_copy(self, copy) 2642 table_expression = maybe_parse( 2643 table, 2644 into=Table, 2645 dialect=dialect, 2646 **opts, 2647 ) 2648 properties_expression = None 2649 if properties: 2650 properties_expression = Properties.from_dict(properties) 2651 2652 return Create( 2653 this=table_expression, 2654 kind="table", 2655 expression=instance, 2656 properties=properties_expression, 2657 )
Convert this expression to a CREATE TABLE AS statement.
Example:
>>> Select().select("*").from_("tbl").ctas("x").sql() 'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
- table (str | Expression): the SQL code string to parse as the table name.
If another
Expressioninstance is passed, it will be used as-is. - properties (dict): an optional mapping of table properties
- dialect (str): the dialect used to parse the input table.
- copy (bool): if
False, modify this expression instance in-place. - opts (kwargs): other options to use to parse the input table.
Returns:
Create: the CREATE TABLE AS expression
2659 def lock(self, update: bool = True, copy: bool = True) -> Select: 2660 """ 2661 Set the locking read mode for this expression. 2662 2663 Examples: 2664 >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") 2665 "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE" 2666 2667 >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") 2668 "SELECT x FROM tbl WHERE x = 'a' FOR SHARE" 2669 2670 Args: 2671 update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`. 2672 copy: if `False`, modify this expression instance in-place. 2673 2674 Returns: 2675 The modified expression. 2676 """ 2677 2678 inst = _maybe_copy(self, copy) 2679 inst.set("lock", Lock(update=update)) 2680 2681 return inst
Set the locking read mode for this expression.
Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE">>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql") "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
- update: if
True, the locking type will beFOR UPDATE, else it will beFOR SHARE. - copy: if
False, modify this expression instance in-place.
Returns:
The modified expression.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2696class Subquery(DerivedTable, Unionable): 2697 arg_types = { 2698 "this": True, 2699 "alias": False, 2700 "with": False, 2701 **QUERY_MODIFIERS, 2702 } 2703 2704 def unnest(self): 2705 """ 2706 Returns the first non subquery. 2707 """ 2708 expression = self 2709 while isinstance(expression, Subquery): 2710 expression = expression.this 2711 return expression 2712 2713 @property 2714 def is_star(self) -> bool: 2715 return self.this.is_star 2716 2717 @property 2718 def output_name(self): 2719 return self.alias
2704 def unnest(self): 2705 """ 2706 Returns the first non subquery. 2707 """ 2708 expression = self 2709 while isinstance(expression, Subquery): 2710 expression = expression.this 2711 return expression
Returns the first non subquery.
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
2722class TableSample(Expression): 2723 arg_types = { 2724 "this": False, 2725 "method": False, 2726 "bucket_numerator": False, 2727 "bucket_denominator": False, 2728 "bucket_field": False, 2729 "percent": False, 2730 "rows": False, 2731 "size": False, 2732 "seed": False, 2733 "kind": False, 2734 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2737class Tag(Expression): 2738 """Tags are used for generating arbitrary sql like SELECT <span>x</span>.""" 2739 2740 arg_types = { 2741 "this": False, 2742 "prefix": False, 2743 "postfix": False, 2744 }
Tags are used for generating arbitrary sql like SELECT x.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2747class Pivot(Expression): 2748 arg_types = { 2749 "this": False, 2750 "alias": False, 2751 "expressions": True, 2752 "field": True, 2753 "unpivot": True, 2754 "columns": False, 2755 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2758class Window(Expression): 2759 arg_types = { 2760 "this": True, 2761 "partition_by": False, 2762 "order": False, 2763 "spec": False, 2764 "alias": False, 2765 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2768class WindowSpec(Expression): 2769 arg_types = { 2770 "kind": False, 2771 "start": False, 2772 "start_side": False, 2773 "end": False, 2774 "end_side": False, 2775 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2782class Star(Expression): 2783 arg_types = {"except": False, "replace": False} 2784 2785 @property 2786 def name(self) -> str: 2787 return "*" 2788 2789 @property 2790 def output_name(self): 2791 return self.name
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2806class Null(Condition): 2807 arg_types: t.Dict[str, t.Any] = {} 2808 2809 @property 2810 def name(self) -> str: 2811 return "NULL"
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2818class DataType(Expression): 2819 arg_types = { 2820 "this": True, 2821 "expressions": False, 2822 "nested": False, 2823 "values": False, 2824 "prefix": False, 2825 } 2826 2827 class Type(AutoName): 2828 CHAR = auto() 2829 NCHAR = auto() 2830 VARCHAR = auto() 2831 NVARCHAR = auto() 2832 TEXT = auto() 2833 MEDIUMTEXT = auto() 2834 LONGTEXT = auto() 2835 MEDIUMBLOB = auto() 2836 LONGBLOB = auto() 2837 BINARY = auto() 2838 VARBINARY = auto() 2839 INT = auto() 2840 UINT = auto() 2841 TINYINT = auto() 2842 UTINYINT = auto() 2843 SMALLINT = auto() 2844 USMALLINT = auto() 2845 BIGINT = auto() 2846 UBIGINT = auto() 2847 FLOAT = auto() 2848 DOUBLE = auto() 2849 DECIMAL = auto() 2850 BIGDECIMAL = auto() 2851 BIT = auto() 2852 BOOLEAN = auto() 2853 JSON = auto() 2854 JSONB = auto() 2855 INTERVAL = auto() 2856 TIME = auto() 2857 TIMESTAMP = auto() 2858 TIMESTAMPTZ = auto() 2859 TIMESTAMPLTZ = auto() 2860 DATE = auto() 2861 DATETIME = auto() 2862 ARRAY = auto() 2863 MAP = auto() 2864 UUID = auto() 2865 GEOGRAPHY = auto() 2866 GEOMETRY = auto() 2867 STRUCT = auto() 2868 NULLABLE = auto() 2869 HLLSKETCH = auto() 2870 HSTORE = auto() 2871 SUPER = auto() 2872 SERIAL = auto() 2873 SMALLSERIAL = auto() 2874 BIGSERIAL = auto() 2875 XML = auto() 2876 UNIQUEIDENTIFIER = auto() 2877 MONEY = auto() 2878 SMALLMONEY = auto() 2879 ROWVERSION = auto() 2880 IMAGE = auto() 2881 VARIANT = auto() 2882 OBJECT = auto() 2883 INET = auto() 2884 NULL = auto() 2885 UNKNOWN = auto() # Sentinel value, useful for type annotation 2886 2887 TEXT_TYPES = { 2888 Type.CHAR, 2889 Type.NCHAR, 2890 Type.VARCHAR, 2891 Type.NVARCHAR, 2892 Type.TEXT, 2893 } 2894 2895 INTEGER_TYPES = { 2896 Type.INT, 2897 Type.TINYINT, 2898 Type.SMALLINT, 2899 Type.BIGINT, 2900 } 2901 2902 FLOAT_TYPES = { 2903 Type.FLOAT, 2904 Type.DOUBLE, 2905 } 2906 2907 NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES} 2908 2909 TEMPORAL_TYPES = { 2910 Type.TIMESTAMP, 2911 Type.TIMESTAMPTZ, 2912 Type.TIMESTAMPLTZ, 2913 Type.DATE, 2914 Type.DATETIME, 2915 } 2916 2917 @classmethod 2918 def build( 2919 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2920 ) -> DataType: 2921 from sqlglot import parse_one 2922 2923 if isinstance(dtype, str): 2924 if dtype.upper() in cls.Type.__members__: 2925 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2926 else: 2927 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2928 if data_type_exp is None: 2929 raise ValueError(f"Unparsable data type value: {dtype}") 2930 elif isinstance(dtype, DataType.Type): 2931 data_type_exp = DataType(this=dtype) 2932 elif isinstance(dtype, DataType): 2933 return dtype 2934 else: 2935 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2936 return DataType(**{**data_type_exp.args, **kwargs}) 2937 2938 def is_type(self, dtype: DataType.Type) -> bool: 2939 return self.this == dtype
2917 @classmethod 2918 def build( 2919 cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs 2920 ) -> DataType: 2921 from sqlglot import parse_one 2922 2923 if isinstance(dtype, str): 2924 if dtype.upper() in cls.Type.__members__: 2925 data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()]) 2926 else: 2927 data_type_exp = parse_one(dtype, read=dialect, into=DataType) 2928 if data_type_exp is None: 2929 raise ValueError(f"Unparsable data type value: {dtype}") 2930 elif isinstance(dtype, DataType.Type): 2931 data_type_exp = DataType(this=dtype) 2932 elif isinstance(dtype, DataType): 2933 return dtype 2934 else: 2935 raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type") 2936 return DataType(**{**data_type_exp.args, **kwargs})
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2827 class Type(AutoName): 2828 CHAR = auto() 2829 NCHAR = auto() 2830 VARCHAR = auto() 2831 NVARCHAR = auto() 2832 TEXT = auto() 2833 MEDIUMTEXT = auto() 2834 LONGTEXT = auto() 2835 MEDIUMBLOB = auto() 2836 LONGBLOB = auto() 2837 BINARY = auto() 2838 VARBINARY = auto() 2839 INT = auto() 2840 UINT = auto() 2841 TINYINT = auto() 2842 UTINYINT = auto() 2843 SMALLINT = auto() 2844 USMALLINT = auto() 2845 BIGINT = auto() 2846 UBIGINT = auto() 2847 FLOAT = auto() 2848 DOUBLE = auto() 2849 DECIMAL = auto() 2850 BIGDECIMAL = auto() 2851 BIT = auto() 2852 BOOLEAN = auto() 2853 JSON = auto() 2854 JSONB = auto() 2855 INTERVAL = auto() 2856 TIME = auto() 2857 TIMESTAMP = auto() 2858 TIMESTAMPTZ = auto() 2859 TIMESTAMPLTZ = auto() 2860 DATE = auto() 2861 DATETIME = auto() 2862 ARRAY = auto() 2863 MAP = auto() 2864 UUID = auto() 2865 GEOGRAPHY = auto() 2866 GEOMETRY = auto() 2867 STRUCT = auto() 2868 NULLABLE = auto() 2869 HLLSKETCH = auto() 2870 HSTORE = auto() 2871 SUPER = auto() 2872 SERIAL = auto() 2873 SMALLSERIAL = auto() 2874 BIGSERIAL = auto() 2875 XML = auto() 2876 UNIQUEIDENTIFIER = auto() 2877 MONEY = auto() 2878 SMALLMONEY = auto() 2879 ROWVERSION = auto() 2880 IMAGE = auto() 2881 VARIANT = auto() 2882 OBJECT = auto() 2883 INET = auto() 2884 NULL = auto() 2885 UNKNOWN = auto() # Sentinel value, useful for type annotation
An enumeration.
Inherited Members
- enum.Enum
- name
- value
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2990class AddConstraint(Expression): 2991 arg_types = {"this": False, "expression": False, "enforced": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
2999class Binary(Expression): 3000 arg_types = {"this": True, "expression": True} 3001 3002 @property 3003 def left(self): 3004 return self.this 3005 3006 @property 3007 def right(self): 3008 return self.expression
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3055class Dot(Binary): 3056 @property 3057 def name(self) -> str: 3058 return self.expression.name 3059 3060 @classmethod 3061 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3062 """Build a Dot object with a sequence of expressions.""" 3063 if len(expressions) < 2: 3064 raise ValueError(f"Dot requires >= 2 expressions.") 3065 3066 a, b, *expressions = expressions 3067 dot = Dot(this=a, expression=b) 3068 3069 for expression in expressions: 3070 dot = Dot(this=dot, expression=expression) 3071 3072 return dot
3060 @classmethod 3061 def build(self, expressions: t.Sequence[Expression]) -> Dot: 3062 """Build a Dot object with a sequence of expressions.""" 3063 if len(expressions) < 2: 3064 raise ValueError(f"Dot requires >= 2 expressions.") 3065 3066 a, b, *expressions = expressions 3067 dot = Dot(this=a, expression=b) 3068 3069 for expression in expressions: 3070 dot = Dot(this=dot, expression=expression) 3071 3072 return dot
Build a Dot object with a sequence of expressions.
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Kwarg in special functions like func(kwarg => y).
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3197class Alias(Expression): 3198 arg_types = {"this": True, "alias": False} 3199 3200 @property 3201 def output_name(self): 3202 return self.alias
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3205class Aliases(Expression): 3206 arg_types = {"this": True, "expressions": True} 3207 3208 @property 3209 def aliases(self): 3210 return self.expressions
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3229class In(Predicate): 3230 arg_types = { 3231 "this": True, 3232 "expressions": False, 3233 "query": False, 3234 "unnest": False, 3235 "field": False, 3236 "is_global": False, 3237 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3240class TimeUnit(Expression): 3241 """Automatically converts unit arg into a var.""" 3242 3243 arg_types = {"unit": False} 3244 3245 def __init__(self, **args): 3246 unit = args.get("unit") 3247 if isinstance(unit, (Column, Literal)): 3248 args["unit"] = Var(this=unit.name) 3249 elif isinstance(unit, Week): 3250 unit.set("this", Var(this=unit.this.name)) 3251 super().__init__(**args)
Automatically converts unit arg into a var.
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3267class Func(Condition): 3268 """ 3269 The base class for all function expressions. 3270 3271 Attributes: 3272 is_var_len_args (bool): if set to True the last argument defined in arg_types will be 3273 treated as a variable length argument and the argument's value will be stored as a list. 3274 _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) 3275 for this function expression. These values are used to map this node to a name during parsing 3276 as well as to provide the function's name during SQL string generation. By default the SQL 3277 name is set to the expression's class name transformed to snake case. 3278 """ 3279 3280 is_var_len_args = False 3281 3282 @classmethod 3283 def from_arg_list(cls, args): 3284 if cls.is_var_len_args: 3285 all_arg_keys = list(cls.arg_types) 3286 # If this function supports variable length argument treat the last argument as such. 3287 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3288 num_non_var = len(non_var_len_arg_keys) 3289 3290 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3291 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3292 else: 3293 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3294 3295 return cls(**args_dict) 3296 3297 @classmethod 3298 def sql_names(cls): 3299 if cls is Func: 3300 raise NotImplementedError( 3301 "SQL name is only supported by concrete function implementations" 3302 ) 3303 if "_sql_names" not in cls.__dict__: 3304 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3305 return cls._sql_names 3306 3307 @classmethod 3308 def sql_name(cls): 3309 return cls.sql_names()[0] 3310 3311 @classmethod 3312 def default_parser_mappings(cls): 3313 return {name: cls.from_arg_list for name in cls.sql_names()}
The base class for all function expressions.
Attributes:
- is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
- _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
3282 @classmethod 3283 def from_arg_list(cls, args): 3284 if cls.is_var_len_args: 3285 all_arg_keys = list(cls.arg_types) 3286 # If this function supports variable length argument treat the last argument as such. 3287 non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys 3288 num_non_var = len(non_var_len_arg_keys) 3289 3290 args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)} 3291 args_dict[all_arg_keys[-1]] = args[num_non_var:] 3292 else: 3293 args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)} 3294 3295 return cls(**args_dict)
3297 @classmethod 3298 def sql_names(cls): 3299 if cls is Func: 3300 raise NotImplementedError( 3301 "SQL name is only supported by concrete function implementations" 3302 ) 3303 if "_sql_names" not in cls.__dict__: 3304 cls._sql_names = [camel_to_snake_case(cls.__name__)] 3305 return cls._sql_names
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3324class Anonymous(Func): 3325 arg_types = {"this": True, "expressions": False} 3326 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3331class Hll(AggFunc): 3332 arg_types = {"this": True, "expressions": False} 3333 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3366class ArrayConcat(Func): 3367 arg_types = {"this": True, "expressions": False} 3368 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3379class ArrayFilter(Func): 3380 arg_types = {"this": True, "expression": True} 3381 _sql_names = ["FILTER", "ARRAY_FILTER"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3416class Cast(Func): 3417 arg_types = {"this": True, "to": True} 3418 3419 @property 3420 def name(self) -> str: 3421 return self.this.name 3422 3423 @property 3424 def to(self): 3425 return self.args["to"] 3426 3427 @property 3428 def output_name(self): 3429 return self.name 3430 3431 def is_type(self, dtype: DataType.Type) -> bool: 3432 return self.to.is_type(dtype)
Name of the output column if this expression is a selection.
If the Expression has no output name, an empty string is returned.
Example:
>>> from sqlglot import parse_one >>> parse_one("SELECT a").expressions[0].output_name 'a' >>> parse_one("SELECT b AS c").expressions[0].output_name 'c' >>> parse_one("SELECT 1 + 2").expressions[0].output_name ''
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3443class Ceil(Func): 3444 arg_types = {"this": True, "decimals": False} 3445 _sql_names = ["CEIL", "CEILING"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3448class Coalesce(Func): 3449 arg_types = {"this": True, "expressions": False} 3450 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3490class DateAdd(Func, TimeUnit): 3491 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3494class DateSub(Func, TimeUnit): 3495 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3498class DateDiff(Func, TimeUnit): 3499 _sql_names = ["DATEDIFF", "DATE_DIFF"] 3500 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3507class DatetimeAdd(Func, TimeUnit): 3508 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3511class DatetimeSub(Func, TimeUnit): 3512 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3515class DatetimeDiff(Func, TimeUnit): 3516 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3519class DatetimeTrunc(Func, TimeUnit): 3520 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3547class TimestampAdd(Func, TimeUnit): 3548 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3551class TimestampSub(Func, TimeUnit): 3552 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3555class TimestampDiff(Func, TimeUnit): 3556 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3559class TimestampTrunc(Func, TimeUnit): 3560 arg_types = {"this": True, "unit": True, "zone": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3563class TimeAdd(Func, TimeUnit): 3564 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3567class TimeSub(Func, TimeUnit): 3568 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3571class TimeDiff(Func, TimeUnit): 3572 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3579class DateFromParts(Func): 3580 _sql_names = ["DATEFROMPARTS"] 3581 arg_types = {"year": True, "month": True, "day": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3620class ExponentialTimeDecayedAvg(AggFunc): 3621 arg_types = {"this": True, "time": False, "decay": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3628class Greatest(Func): 3629 arg_types = {"this": True, "expressions": False} 3630 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3653class IfNull(Func): 3654 arg_types = {"this": True, "expression": False} 3655 _sql_names = ["IFNULL", "NVL"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3666class JSONObject(Func): 3667 arg_types = { 3668 "expressions": False, 3669 "null_handling": False, 3670 "unique_keys": False, 3671 "return_type": False, 3672 "format_json": False, 3673 "encoding": False, 3674 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3697class JSONFormat(Func): 3698 arg_types = {"this": False, "options": False} 3699 _sql_names = ["JSON_FORMAT"]
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3711class Levenshtein(Func): 3712 arg_types = { 3713 "this": True, 3714 "expression": False, 3715 "ins_cost": False, 3716 "del_cost": False, 3717 "sub_cost": False, 3718 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3759class MatchAgainst(Func): 3760 arg_types = {"this": True, "expressions": True, "modifier": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3763class Max(AggFunc): 3764 arg_types = {"this": True, "expressions": False} 3765 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3768class Min(AggFunc): 3769 arg_types = {"this": True, "expressions": False} 3770 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3803class Quantiles(AggFunc): 3804 arg_types = {"parameters": True, "expressions": True} 3805 is_var_len_args = True
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3812class ApproxQuantile(Quantile): 3813 arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3820class ReadCSV(Func): 3821 _sql_names = ["READ_CSV"] 3822 is_var_len_args = True 3823 arg_types = {"this": True, "expressions": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3826class Reduce(Func): 3827 arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3830class RegexpExtract(Func): 3831 arg_types = { 3832 "this": True, 3833 "expression": True, 3834 "position": False, 3835 "occurrence": False, 3836 "group": False, 3837 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3888class StrPosition(Func): 3889 arg_types = { 3890 "this": True, 3891 "substr": True, 3892 "position": False, 3893 "instance": False, 3894 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3968class Trim(Func): 3969 arg_types = { 3970 "this": True, 3971 "expression": False, 3972 "position": False, 3973 "collation": False, 3974 }
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
3977class TsOrDsAdd(Func, TimeUnit): 3978 arg_types = {"this": True, "expression": True, "unit": False}
Inherited Members
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4003class UnixToTime(Func): 4004 arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False} 4005 4006 SECONDS = Literal.string("seconds") 4007 MILLIS = Literal.string("millis") 4008 MICROS = Literal.string("micros")
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4031class XMLTable(Func): 4032 arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4043class Merge(Expression): 4044 arg_types = {"this": True, "using": True, "on": True, "expressions": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4047class When(Func): 4048 arg_types = {"matched": True, "source": False, "condition": False, "then": True}
Inherited Members
- Expression
- Expression
- this
- expression
- expressions
- text
- is_string
- is_number
- is_int
- is_star
- alias
- output_name
- copy
- append
- set
- depth
- iter_expressions
- find
- find_all
- find_ancestor
- parent_select
- same_parent
- root
- walk
- dfs
- bfs
- unnest
- unalias
- unnest_operands
- flatten
- sql
- transform
- replace
- pop
- assert_is
- error_messages
- dump
- load
4085def maybe_parse( 4086 sql_or_expression: ExpOrStr, 4087 *, 4088 into: t.Optional[IntoType] = None, 4089 dialect: DialectType = None, 4090 prefix: t.Optional[str] = None, 4091 copy: bool = False, 4092 **opts, 4093) -> Expression: 4094 """Gracefully handle a possible string or expression. 4095 4096 Example: 4097 >>> maybe_parse("1") 4098 (LITERAL this: 1, is_string: False) 4099 >>> maybe_parse(to_identifier("x")) 4100 (IDENTIFIER this: x, quoted: False) 4101 4102 Args: 4103 sql_or_expression: the SQL code string or an expression 4104 into: the SQLGlot Expression to parse into 4105 dialect: the dialect used to parse the input expressions (in the case that an 4106 input expression is a SQL string). 4107 prefix: a string to prefix the sql with before it gets parsed 4108 (automatically includes a space) 4109 copy: whether or not to copy the expression. 4110 **opts: other options to use to parse the input expressions (again, in the case 4111 that an input expression is a SQL string). 4112 4113 Returns: 4114 Expression: the parsed or given expression. 4115 """ 4116 if isinstance(sql_or_expression, Expression): 4117 if copy: 4118 return sql_or_expression.copy() 4119 return sql_or_expression 4120 4121 import sqlglot 4122 4123 sql = str(sql_or_expression) 4124 if prefix: 4125 sql = f"{prefix} {sql}" 4126 return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
Gracefully handle a possible string or expression.
Example:
>>> maybe_parse("1") (LITERAL this: 1, is_string: False) >>> maybe_parse(to_identifier("x")) (IDENTIFIER this: x, quoted: False)
Arguments:
- sql_or_expression: the SQL code string or an expression
- into: the SQLGlot Expression to parse into
- dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
- prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
- copy: whether or not to copy the expression.
- **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:
Expression: the parsed or given expression.
4272def union(left, right, distinct=True, dialect=None, **opts): 4273 """ 4274 Initializes a syntax tree from one UNION expression. 4275 4276 Example: 4277 >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 4278 'SELECT * FROM foo UNION SELECT * FROM bla' 4279 4280 Args: 4281 left (str | Expression): the SQL code string corresponding to the left-hand side. 4282 If an `Expression` instance is passed, it will be used as-is. 4283 right (str | Expression): the SQL code string corresponding to the right-hand side. 4284 If an `Expression` instance is passed, it will be used as-is. 4285 distinct (bool): set the DISTINCT flag if and only if this is true. 4286 dialect (str): the dialect used to parse the input expression. 4287 opts (kwargs): other options to use to parse the input expressions. 4288 Returns: 4289 Union: the syntax tree for the UNION expression. 4290 """ 4291 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4292 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4293 4294 return Union(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one UNION expression.
Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Union: the syntax tree for the UNION expression.
4297def intersect(left, right, distinct=True, dialect=None, **opts): 4298 """ 4299 Initializes a syntax tree from one INTERSECT expression. 4300 4301 Example: 4302 >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 4303 'SELECT * FROM foo INTERSECT SELECT * FROM bla' 4304 4305 Args: 4306 left (str | Expression): the SQL code string corresponding to the left-hand side. 4307 If an `Expression` instance is passed, it will be used as-is. 4308 right (str | Expression): the SQL code string corresponding to the right-hand side. 4309 If an `Expression` instance is passed, it will be used as-is. 4310 distinct (bool): set the DISTINCT flag if and only if this is true. 4311 dialect (str): the dialect used to parse the input expression. 4312 opts (kwargs): other options to use to parse the input expressions. 4313 Returns: 4314 Intersect: the syntax tree for the INTERSECT expression. 4315 """ 4316 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4317 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4318 4319 return Intersect(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one INTERSECT expression.
Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Intersect: the syntax tree for the INTERSECT expression.
4322def except_(left, right, distinct=True, dialect=None, **opts): 4323 """ 4324 Initializes a syntax tree from one EXCEPT expression. 4325 4326 Example: 4327 >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 4328 'SELECT * FROM foo EXCEPT SELECT * FROM bla' 4329 4330 Args: 4331 left (str | Expression): the SQL code string corresponding to the left-hand side. 4332 If an `Expression` instance is passed, it will be used as-is. 4333 right (str | Expression): the SQL code string corresponding to the right-hand side. 4334 If an `Expression` instance is passed, it will be used as-is. 4335 distinct (bool): set the DISTINCT flag if and only if this is true. 4336 dialect (str): the dialect used to parse the input expression. 4337 opts (kwargs): other options to use to parse the input expressions. 4338 Returns: 4339 Except: the syntax tree for the EXCEPT statement. 4340 """ 4341 left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts) 4342 right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts) 4343 4344 return Except(this=left, expression=right, distinct=distinct)
Initializes a syntax tree from one EXCEPT expression.
Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql() 'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
- left (str | Expression): the SQL code string corresponding to the left-hand side.
If an
Expressioninstance is passed, it will be used as-is. - right (str | Expression): the SQL code string corresponding to the right-hand side.
If an
Expressioninstance is passed, it will be used as-is. - distinct (bool): set the DISTINCT flag if and only if this is true.
- dialect (str): the dialect used to parse the input expression.
- opts (kwargs): other options to use to parse the input expressions.
Returns:
Except: the syntax tree for the EXCEPT statement.
4347def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select: 4348 """ 4349 Initializes a syntax tree from one or multiple SELECT expressions. 4350 4351 Example: 4352 >>> select("col1", "col2").from_("tbl").sql() 4353 'SELECT col1, col2 FROM tbl' 4354 4355 Args: 4356 *expressions: the SQL code string to parse as the expressions of a 4357 SELECT statement. If an Expression instance is passed, this is used as-is. 4358 dialect: the dialect used to parse the input expressions (in the case that an 4359 input expression is a SQL string). 4360 **opts: other options to use to parse the input expressions (again, in the case 4361 that an input expression is a SQL string). 4362 4363 Returns: 4364 Select: the syntax tree for the SELECT statement. 4365 """ 4366 return Select().select(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from one or multiple SELECT expressions.
Example:
>>> select("col1", "col2").from_("tbl").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4369def from_(*expressions, dialect=None, **opts) -> Select: 4370 """ 4371 Initializes a syntax tree from a FROM expression. 4372 4373 Example: 4374 >>> from_("tbl").select("col1", "col2").sql() 4375 'SELECT col1, col2 FROM tbl' 4376 4377 Args: 4378 *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a 4379 SELECT statement. If an Expression instance is passed, this is used as-is. 4380 dialect (str): the dialect used to parse the input expression (in the case that the 4381 input expression is a SQL string). 4382 **opts: other options to use to parse the input expressions (again, in the case 4383 that the input expression is a SQL string). 4384 4385 Returns: 4386 Select: the syntax tree for the SELECT statement. 4387 """ 4388 return Select().from_(*expressions, dialect=dialect, **opts)
Initializes a syntax tree from a FROM expression.
Example:
>>> from_("tbl").select("col1", "col2").sql() 'SELECT col1, col2 FROM tbl'
Arguments:
- *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Select: the syntax tree for the SELECT statement.
4391def update( 4392 table: str | Table, 4393 properties: dict, 4394 where: t.Optional[ExpOrStr] = None, 4395 from_: t.Optional[ExpOrStr] = None, 4396 dialect: DialectType = None, 4397 **opts, 4398) -> Update: 4399 """ 4400 Creates an update statement. 4401 4402 Example: 4403 >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() 4404 "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1" 4405 4406 Args: 4407 *properties: dictionary of properties to set which are 4408 auto converted to sql objects eg None -> NULL 4409 where: sql conditional parsed into a WHERE statement 4410 from_: sql statement parsed into a FROM statement 4411 dialect: the dialect used to parse the input expressions. 4412 **opts: other options to use to parse the input expressions. 4413 4414 Returns: 4415 Update: the syntax tree for the UPDATE statement. 4416 """ 4417 update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect)) 4418 update_expr.set( 4419 "expressions", 4420 [ 4421 EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v)) 4422 for k, v in properties.items() 4423 ], 4424 ) 4425 if from_: 4426 update_expr.set( 4427 "from", 4428 maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts), 4429 ) 4430 if isinstance(where, Condition): 4431 where = Where(this=where) 4432 if where: 4433 update_expr.set( 4434 "where", 4435 maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts), 4436 ) 4437 return update_expr
Creates an update statement.
Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql() "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
- *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
- where: sql conditional parsed into a WHERE statement
- from_: sql statement parsed into a FROM statement
- dialect: the dialect used to parse the input expressions.
- **opts: other options to use to parse the input expressions.
Returns:
Update: the syntax tree for the UPDATE statement.
4440def delete( 4441 table: ExpOrStr, 4442 where: t.Optional[ExpOrStr] = None, 4443 returning: t.Optional[ExpOrStr] = None, 4444 dialect: DialectType = None, 4445 **opts, 4446) -> Delete: 4447 """ 4448 Builds a delete statement. 4449 4450 Example: 4451 >>> delete("my_table", where="id > 1").sql() 4452 'DELETE FROM my_table WHERE id > 1' 4453 4454 Args: 4455 where: sql conditional parsed into a WHERE statement 4456 returning: sql conditional parsed into a RETURNING statement 4457 dialect: the dialect used to parse the input expressions. 4458 **opts: other options to use to parse the input expressions. 4459 4460 Returns: 4461 Delete: the syntax tree for the DELETE statement. 4462 """ 4463 delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts) 4464 if where: 4465 delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts) 4466 if returning: 4467 delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts) 4468 return delete_expr
Builds a delete statement.
Example:
>>> delete("my_table", where="id > 1").sql() 'DELETE FROM my_table WHERE id > 1'
Arguments:
- where: sql conditional parsed into a WHERE statement
- returning: sql conditional parsed into a RETURNING statement
- dialect: the dialect used to parse the input expressions.
- **opts: other options to use to parse the input expressions.
Returns:
Delete: the syntax tree for the DELETE statement.
4471def condition(expression, dialect=None, **opts) -> Condition: 4472 """ 4473 Initialize a logical condition expression. 4474 4475 Example: 4476 >>> condition("x=1").sql() 4477 'x = 1' 4478 4479 This is helpful for composing larger logical syntax trees: 4480 >>> where = condition("x=1") 4481 >>> where = where.and_("y=1") 4482 >>> Select().from_("tbl").select("*").where(where).sql() 4483 'SELECT * FROM tbl WHERE x = 1 AND y = 1' 4484 4485 Args: 4486 *expression (str | Expression): the SQL code string to parse. 4487 If an Expression instance is passed, this is used as-is. 4488 dialect (str): the dialect used to parse the input expression (in the case that the 4489 input expression is a SQL string). 4490 **opts: other options to use to parse the input expressions (again, in the case 4491 that the input expression is a SQL string). 4492 4493 Returns: 4494 Condition: the expression 4495 """ 4496 return maybe_parse( # type: ignore 4497 expression, 4498 into=Condition, 4499 dialect=dialect, 4500 **opts, 4501 )
Initialize a logical condition expression.
Example:
>>> condition("x=1").sql() 'x = 1'This is helpful for composing larger logical syntax trees:
>>> where = condition("x=1") >>> where = where.and_("y=1") >>> Select().from_("tbl").select("*").where(where).sql() 'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
- *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
- **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:
Condition: the expression
4504def and_(*expressions, dialect=None, **opts) -> And: 4505 """ 4506 Combine multiple conditions with an AND logical operator. 4507 4508 Example: 4509 >>> and_("x=1", and_("y=1", "z=1")).sql() 4510 'x = 1 AND (y = 1 AND z = 1)' 4511 4512 Args: 4513 *expressions (str | Expression): the SQL code strings to parse. 4514 If an Expression instance is passed, this is used as-is. 4515 dialect (str): the dialect used to parse the input expression. 4516 **opts: other options to use to parse the input expressions. 4517 4518 Returns: 4519 And: the new condition 4520 """ 4521 return _combine(expressions, And, dialect, **opts)
Combine multiple conditions with an AND logical operator.
Example:
>>> and_("x=1", and_("y=1", "z=1")).sql() 'x = 1 AND (y = 1 AND z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
And: the new condition
4524def or_(*expressions, dialect=None, **opts) -> Or: 4525 """ 4526 Combine multiple conditions with an OR logical operator. 4527 4528 Example: 4529 >>> or_("x=1", or_("y=1", "z=1")).sql() 4530 'x = 1 OR (y = 1 OR z = 1)' 4531 4532 Args: 4533 *expressions (str | Expression): the SQL code strings to parse. 4534 If an Expression instance is passed, this is used as-is. 4535 dialect (str): the dialect used to parse the input expression. 4536 **opts: other options to use to parse the input expressions. 4537 4538 Returns: 4539 Or: the new condition 4540 """ 4541 return _combine(expressions, Or, dialect, **opts)
Combine multiple conditions with an OR logical operator.
Example:
>>> or_("x=1", or_("y=1", "z=1")).sql() 'x = 1 OR (y = 1 OR z = 1)'
Arguments:
- *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Or: the new condition
4544def not_(expression, dialect=None, **opts) -> Not: 4545 """ 4546 Wrap a condition with a NOT operator. 4547 4548 Example: 4549 >>> not_("this_suit='black'").sql() 4550 "NOT this_suit = 'black'" 4551 4552 Args: 4553 expression (str | Expression): the SQL code strings to parse. 4554 If an Expression instance is passed, this is used as-is. 4555 dialect (str): the dialect used to parse the input expression. 4556 **opts: other options to use to parse the input expressions. 4557 4558 Returns: 4559 Not: the new condition 4560 """ 4561 this = condition( 4562 expression, 4563 dialect=dialect, 4564 **opts, 4565 ) 4566 return Not(this=_wrap_operator(this))
Wrap a condition with a NOT operator.
Example:
>>> not_("this_suit='black'").sql() "NOT this_suit = 'black'"
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Not: the new condition
4586def to_identifier(name, quoted=None): 4587 """Builds an identifier. 4588 4589 Args: 4590 name: The name to turn into an identifier. 4591 quoted: Whether or not force quote the identifier. 4592 4593 Returns: 4594 The identifier ast node. 4595 """ 4596 4597 if name is None: 4598 return None 4599 4600 if isinstance(name, Identifier): 4601 identifier = name 4602 elif isinstance(name, str): 4603 identifier = Identifier( 4604 this=name, 4605 quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted, 4606 ) 4607 else: 4608 raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}") 4609 return identifier
Builds an identifier.
Arguments:
- name: The name to turn into an identifier.
- quoted: Whether or not force quote the identifier.
Returns:
The identifier ast node.
4615def to_interval(interval: str | Literal) -> Interval: 4616 """Builds an interval expression from a string like '1 day' or '5 months'.""" 4617 if isinstance(interval, Literal): 4618 if not interval.is_string: 4619 raise ValueError("Invalid interval string.") 4620 4621 interval = interval.this 4622 4623 interval_parts = INTERVAL_STRING_RE.match(interval) # type: ignore 4624 4625 if not interval_parts: 4626 raise ValueError("Invalid interval string.") 4627 4628 return Interval( 4629 this=Literal.string(interval_parts.group(1)), 4630 unit=Var(this=interval_parts.group(2)), 4631 )
Builds an interval expression from a string like '1 day' or '5 months'.
4644def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]: 4645 """ 4646 Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional. 4647 If a table is passed in then that table is returned. 4648 4649 Args: 4650 sql_path: a `[catalog].[schema].[table]` string. 4651 4652 Returns: 4653 A table expression. 4654 """ 4655 if sql_path is None or isinstance(sql_path, Table): 4656 return sql_path 4657 if not isinstance(sql_path, str): 4658 raise ValueError(f"Invalid type provided for a table: {type(sql_path)}") 4659 4660 catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3)) 4661 return Table(this=table_name, db=db, catalog=catalog, **kwargs)
Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional.
If a table is passed in then that table is returned.
Arguments:
- sql_path: a
[catalog].[schema].[table]string.
Returns:
A table expression.
4664def to_column(sql_path: str | Column, **kwargs) -> Column: 4665 """ 4666 Create a column from a `[table].[column]` sql path. Schema is optional. 4667 4668 If a column is passed in then that column is returned. 4669 4670 Args: 4671 sql_path: `[table].[column]` string 4672 Returns: 4673 Table: A column expression 4674 """ 4675 if sql_path is None or isinstance(sql_path, Column): 4676 return sql_path 4677 if not isinstance(sql_path, str): 4678 raise ValueError(f"Invalid type provided for column: {type(sql_path)}") 4679 return column(*reversed(sql_path.split(".")), **kwargs) # type: ignore
Create a column from a [table].[column] sql path. Schema is optional.
If a column is passed in then that column is returned.
Arguments:
- sql_path:
[table].[column]string
Returns:
Table: A column expression
4682def alias_( 4683 expression: ExpOrStr, 4684 alias: str | Identifier, 4685 table: bool | t.Sequence[str | Identifier] = False, 4686 quoted: t.Optional[bool] = None, 4687 dialect: DialectType = None, 4688 **opts, 4689): 4690 """Create an Alias expression. 4691 4692 Example: 4693 >>> alias_('foo', 'bar').sql() 4694 'foo AS bar' 4695 4696 >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() 4697 '(SELECT 1, 2) AS bar(a, b)' 4698 4699 Args: 4700 expression: the SQL code strings to parse. 4701 If an Expression instance is passed, this is used as-is. 4702 alias: the alias name to use. If the name has 4703 special characters it is quoted. 4704 table: Whether or not to create a table alias, can also be a list of columns. 4705 quoted: whether or not to quote the alias 4706 dialect: the dialect used to parse the input expression. 4707 **opts: other options to use to parse the input expressions. 4708 4709 Returns: 4710 Alias: the aliased expression 4711 """ 4712 exp = maybe_parse(expression, dialect=dialect, **opts) 4713 alias = to_identifier(alias, quoted=quoted) 4714 4715 if table: 4716 table_alias = TableAlias(this=alias) 4717 exp.set("alias", table_alias) 4718 4719 if not isinstance(table, bool): 4720 for column in table: 4721 table_alias.append("columns", to_identifier(column, quoted=quoted)) 4722 4723 return exp 4724 4725 # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in 4726 # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node 4727 # for the complete Window expression. 4728 # 4729 # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls 4730 4731 if "alias" in exp.arg_types and not isinstance(exp, Window): 4732 exp = exp.copy() 4733 exp.set("alias", alias) 4734 return exp 4735 return Alias(this=exp, alias=alias)
Create an Alias expression.
Example:
>>> alias_('foo', 'bar').sql() 'foo AS bar'>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql() '(SELECT 1, 2) AS bar(a, b)'
Arguments:
- expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias: the alias name to use. If the name has special characters it is quoted.
- table: Whether or not to create a table alias, can also be a list of columns.
- quoted: whether or not to quote the alias
- dialect: the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Alias: the aliased expression
4738def subquery(expression, alias=None, dialect=None, **opts): 4739 """ 4740 Build a subquery expression. 4741 4742 Example: 4743 >>> subquery('select x from tbl', 'bar').select('x').sql() 4744 'SELECT x FROM (SELECT x FROM tbl) AS bar' 4745 4746 Args: 4747 expression (str | Expression): the SQL code strings to parse. 4748 If an Expression instance is passed, this is used as-is. 4749 alias (str | Expression): the alias name to use. 4750 dialect (str): the dialect used to parse the input expression. 4751 **opts: other options to use to parse the input expressions. 4752 4753 Returns: 4754 Select: a new select with the subquery expression included 4755 """ 4756 4757 expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias) 4758 return Select().from_(expression, dialect=dialect, **opts)
Build a subquery expression.
Example:
>>> subquery('select x from tbl', 'bar').select('x').sql() 'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
- expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
- alias (str | Expression): the alias name to use.
- dialect (str): the dialect used to parse the input expression.
- **opts: other options to use to parse the input expressions.
Returns:
Select: a new select with the subquery expression included
4761def column( 4762 col: str | Identifier, 4763 table: t.Optional[str | Identifier] = None, 4764 db: t.Optional[str | Identifier] = None, 4765 catalog: t.Optional[str | Identifier] = None, 4766 quoted: t.Optional[bool] = None, 4767) -> Column: 4768 """ 4769 Build a Column. 4770 4771 Args: 4772 col: column name 4773 table: table name 4774 db: db name 4775 catalog: catalog name 4776 quoted: whether or not to force quote each part 4777 Returns: 4778 Column: column instance 4779 """ 4780 return Column( 4781 this=to_identifier(col, quoted=quoted), 4782 table=to_identifier(table, quoted=quoted), 4783 db=to_identifier(db, quoted=quoted), 4784 catalog=to_identifier(catalog, quoted=quoted), 4785 )
Build a Column.
Arguments:
- col: column name
- table: table name
- db: db name
- catalog: catalog name
- quoted: whether or not to force quote each part
Returns:
Column: column instance
4788def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast: 4789 """Cast an expression to a data type. 4790 4791 Example: 4792 >>> cast('x + 1', 'int').sql() 4793 'CAST(x + 1 AS INT)' 4794 4795 Args: 4796 expression: The expression to cast. 4797 to: The datatype to cast to. 4798 4799 Returns: 4800 A cast node. 4801 """ 4802 expression = maybe_parse(expression, **opts) 4803 return Cast(this=expression, to=DataType.build(to, **opts))
Cast an expression to a data type.
Example:
>>> cast('x + 1', 'int').sql() 'CAST(x + 1 AS INT)'
Arguments:
- expression: The expression to cast.
- to: The datatype to cast to.
Returns:
A cast node.
4806def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table: 4807 """Build a Table. 4808 4809 Args: 4810 table (str | Expression): column name 4811 db (str | Expression): db name 4812 catalog (str | Expression): catalog name 4813 4814 Returns: 4815 Table: table instance 4816 """ 4817 return Table( 4818 this=to_identifier(table, quoted=quoted), 4819 db=to_identifier(db, quoted=quoted), 4820 catalog=to_identifier(catalog, quoted=quoted), 4821 alias=TableAlias(this=to_identifier(alias)) if alias else None, 4822 )
Build a Table.
Arguments:
- table (str | Expression): column name
- db (str | Expression): db name
- catalog (str | Expression): catalog name
Returns:
Table: table instance
4825def values( 4826 values: t.Iterable[t.Tuple[t.Any, ...]], 4827 alias: t.Optional[str] = None, 4828 columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None, 4829) -> Values: 4830 """Build VALUES statement. 4831 4832 Example: 4833 >>> values([(1, '2')]).sql() 4834 "VALUES (1, '2')" 4835 4836 Args: 4837 values: values statements that will be converted to SQL 4838 alias: optional alias 4839 columns: Optional list of ordered column names or ordered dictionary of column names to types. 4840 If either are provided then an alias is also required. 4841 If a dictionary is provided then the first column of the values will be casted to the expected type 4842 in order to help with type inference. 4843 4844 Returns: 4845 Values: the Values expression object 4846 """ 4847 if columns and not alias: 4848 raise ValueError("Alias is required when providing columns") 4849 table_alias = ( 4850 TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns]) 4851 if columns 4852 else TableAlias(this=to_identifier(alias) if alias else None) 4853 ) 4854 expressions = [convert(tup) for tup in values] 4855 if columns and isinstance(columns, dict): 4856 types = list(columns.values()) 4857 expressions[0].set( 4858 "expressions", 4859 [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)], 4860 ) 4861 return Values( 4862 expressions=expressions, 4863 alias=table_alias, 4864 )
Build VALUES statement.
Example:
>>> values([(1, '2')]).sql() "VALUES (1, '2')"
Arguments:
- values: values statements that will be converted to SQL
- alias: optional alias
- columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:
Values: the Values expression object
4867def var(name: t.Optional[ExpOrStr]) -> Var: 4868 """Build a SQL variable. 4869 4870 Example: 4871 >>> repr(var('x')) 4872 '(VAR this: x)' 4873 4874 >>> repr(var(column('x', table='y'))) 4875 '(VAR this: x)' 4876 4877 Args: 4878 name: The name of the var or an expression who's name will become the var. 4879 4880 Returns: 4881 The new variable node. 4882 """ 4883 if not name: 4884 raise ValueError("Cannot convert empty name into var.") 4885 4886 if isinstance(name, Expression): 4887 name = name.name 4888 return Var(this=name)
Build a SQL variable.
Example:
>>> repr(var('x')) '(VAR this: x)'>>> repr(var(column('x', table='y'))) '(VAR this: x)'
Arguments:
- name: The name of the var or an expression who's name will become the var.
Returns:
The new variable node.
4891def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable: 4892 """Build ALTER TABLE... RENAME... expression 4893 4894 Args: 4895 old_name: The old name of the table 4896 new_name: The new name of the table 4897 4898 Returns: 4899 Alter table expression 4900 """ 4901 old_table = to_table(old_name) 4902 new_table = to_table(new_name) 4903 return AlterTable( 4904 this=old_table, 4905 actions=[ 4906 RenameTable(this=new_table), 4907 ], 4908 )
Build ALTER TABLE... RENAME... expression
Arguments:
- old_name: The old name of the table
- new_name: The new name of the table
Returns:
Alter table expression
4911def convert(value) -> Expression: 4912 """Convert a python value into an expression object. 4913 4914 Raises an error if a conversion is not possible. 4915 4916 Args: 4917 value (Any): a python object 4918 4919 Returns: 4920 Expression: the equivalent expression object 4921 """ 4922 if isinstance(value, Expression): 4923 return value 4924 if value is None: 4925 return NULL 4926 if isinstance(value, bool): 4927 return Boolean(this=value) 4928 if isinstance(value, str): 4929 return Literal.string(value) 4930 if isinstance(value, float) and math.isnan(value): 4931 return NULL 4932 if isinstance(value, numbers.Number): 4933 return Literal.number(value) 4934 if isinstance(value, tuple): 4935 return Tuple(expressions=[convert(v) for v in value]) 4936 if isinstance(value, list): 4937 return Array(expressions=[convert(v) for v in value]) 4938 if isinstance(value, dict): 4939 return Map( 4940 keys=[convert(k) for k in value], 4941 values=[convert(v) for v in value.values()], 4942 ) 4943 if isinstance(value, datetime.datetime): 4944 datetime_literal = Literal.string( 4945 (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat() 4946 ) 4947 return TimeStrToTime(this=datetime_literal) 4948 if isinstance(value, datetime.date): 4949 date_literal = Literal.string(value.strftime("%Y-%m-%d")) 4950 return DateStrToDate(this=date_literal) 4951 raise ValueError(f"Cannot convert {value}")
Convert a python value into an expression object.
Raises an error if a conversion is not possible.
Arguments:
- value (Any): a python object
Returns:
Expression: the equivalent expression object
4954def replace_children(expression, fun, *args, **kwargs): 4955 """ 4956 Replace children of an expression with the result of a lambda fun(child) -> exp. 4957 """ 4958 for k, v in expression.args.items(): 4959 is_list_arg = type(v) is list 4960 4961 child_nodes = v if is_list_arg else [v] 4962 new_child_nodes = [] 4963 4964 for cn in child_nodes: 4965 if isinstance(cn, Expression): 4966 for child_node in ensure_collection(fun(cn, *args, **kwargs)): 4967 new_child_nodes.append(child_node) 4968 child_node.parent = expression 4969 child_node.arg_key = k 4970 else: 4971 new_child_nodes.append(cn) 4972 4973 expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
Replace children of an expression with the result of a lambda fun(child) -> exp.
4976def column_table_names(expression): 4977 """ 4978 Return all table names referenced through columns in an expression. 4979 4980 Example: 4981 >>> import sqlglot 4982 >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) 4983 ['c', 'a'] 4984 4985 Args: 4986 expression (sqlglot.Expression): expression to find table names 4987 4988 Returns: 4989 list: A list of unique names 4990 """ 4991 return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
Return all table names referenced through columns in an expression.
Example:
>>> import sqlglot >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")) ['c', 'a']
Arguments:
- expression (sqlglot.Expression): expression to find table names
Returns:
list: A list of unique names
4994def table_name(table) -> str: 4995 """Get the full name of a table as a string. 4996 4997 Args: 4998 table (exp.Table | str): table expression node or string. 4999 5000 Examples: 5001 >>> from sqlglot import exp, parse_one 5002 >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 5003 'a.b.c' 5004 5005 Returns: 5006 The table name. 5007 """ 5008 5009 table = maybe_parse(table, into=Table) 5010 5011 if not table: 5012 raise ValueError(f"Cannot parse {table}") 5013 5014 return ".".join( 5015 part 5016 for part in ( 5017 table.text("catalog"), 5018 table.text("db"), 5019 table.name, 5020 ) 5021 if part 5022 )
Get the full name of a table as a string.
Arguments:
- table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one >>> table_name(parse_one("select * from a.b.c").find(exp.Table)) 'a.b.c'
Returns:
The table name.
5025def replace_tables(expression, mapping): 5026 """Replace all tables in expression according to the mapping. 5027 5028 Args: 5029 expression (sqlglot.Expression): expression node to be transformed and replaced. 5030 mapping (Dict[str, str]): mapping of table names. 5031 5032 Examples: 5033 >>> from sqlglot import exp, parse_one 5034 >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 5035 'SELECT * FROM c' 5036 5037 Returns: 5038 The mapped expression. 5039 """ 5040 5041 def _replace_tables(node): 5042 if isinstance(node, Table): 5043 new_name = mapping.get(table_name(node)) 5044 if new_name: 5045 return to_table( 5046 new_name, 5047 **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")}, 5048 ) 5049 return node 5050 5051 return expression.transform(_replace_tables)
Replace all tables in expression according to the mapping.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql() 'SELECT * FROM c'
Returns:
The mapped expression.
5054def replace_placeholders(expression, *args, **kwargs): 5055 """Replace placeholders in an expression. 5056 5057 Args: 5058 expression (sqlglot.Expression): expression node to be transformed and replaced. 5059 args: positional names that will substitute unnamed placeholders in the given order. 5060 kwargs: keyword arguments that will substitute named placeholders. 5061 5062 Examples: 5063 >>> from sqlglot import exp, parse_one 5064 >>> replace_placeholders( 5065 ... parse_one("select * from :tbl where ? = ?"), 5066 ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") 5067 ... ).sql() 5068 "SELECT * FROM foo WHERE str_col = 'b'" 5069 5070 Returns: 5071 The mapped expression. 5072 """ 5073 5074 def _replace_placeholders(node, args, **kwargs): 5075 if isinstance(node, Placeholder): 5076 if node.name: 5077 new_name = kwargs.get(node.name) 5078 if new_name: 5079 return convert(new_name) 5080 else: 5081 try: 5082 return convert(next(args)) 5083 except StopIteration: 5084 pass 5085 return node 5086 5087 return expression.transform(_replace_placeholders, iter(args), **kwargs)
Replace placeholders in an expression.
Arguments:
- expression (sqlglot.Expression): expression node to be transformed and replaced.
- args: positional names that will substitute unnamed placeholders in the given order.
- kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one >>> replace_placeholders( ... parse_one("select * from :tbl where ? = ?"), ... exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo") ... ).sql() "SELECT * FROM foo WHERE str_col = 'b'"
Returns:
The mapped expression.
5090def expand( 5091 expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True 5092) -> Expression: 5093 """Transforms an expression by expanding all referenced sources into subqueries. 5094 5095 Examples: 5096 >>> from sqlglot import parse_one 5097 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 5098 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */' 5099 5100 >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 5101 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */' 5102 5103 Args: 5104 expression: The expression to expand. 5105 sources: A dictionary of name to Subqueryables. 5106 copy: Whether or not to copy the expression during transformation. Defaults to True. 5107 5108 Returns: 5109 The transformed expression. 5110 """ 5111 5112 def _expand(node: Expression): 5113 if isinstance(node, Table): 5114 name = table_name(node) 5115 source = sources.get(name) 5116 if source: 5117 subquery = source.subquery(node.alias or name) 5118 subquery.comments = [f"source: {name}"] 5119 return subquery.transform(_expand, copy=False) 5120 return node 5121 5122 return expression.transform(_expand, copy=copy)
Transforms an expression by expanding all referenced sources into subqueries.
Examples:
>>> from sqlglot import parse_one >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql() 'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql() 'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
- expression: The expression to expand.
- sources: A dictionary of name to Subqueryables.
- copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:
The transformed expression.
5125def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func: 5126 """ 5127 Returns a Func expression. 5128 5129 Examples: 5130 >>> func("abs", 5).sql() 5131 'ABS(5)' 5132 5133 >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 5134 'CAST(5 AS DOUBLE)' 5135 5136 Args: 5137 name: the name of the function to build. 5138 args: the args used to instantiate the function of interest. 5139 dialect: the source dialect. 5140 kwargs: the kwargs used to instantiate the function of interest. 5141 5142 Note: 5143 The arguments `args` and `kwargs` are mutually exclusive. 5144 5145 Returns: 5146 An instance of the function of interest, or an anonymous function, if `name` doesn't 5147 correspond to an existing `sqlglot.expressions.Func` class. 5148 """ 5149 if args and kwargs: 5150 raise ValueError("Can't use both args and kwargs to instantiate a function.") 5151 5152 from sqlglot.dialects.dialect import Dialect 5153 5154 converted = [convert(arg) for arg in args] 5155 kwargs = {key: convert(value) for key, value in kwargs.items()} 5156 5157 parser = Dialect.get_or_raise(dialect)().parser() 5158 from_args_list = parser.FUNCTIONS.get(name.upper()) 5159 5160 if from_args_list: 5161 function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs) # type: ignore 5162 else: 5163 kwargs = kwargs or {"expressions": converted} 5164 function = Anonymous(this=name, **kwargs) 5165 5166 for error_message in function.error_messages(converted): 5167 raise ValueError(error_message) 5168 5169 return function
Returns a Func expression.
Examples:
>>> func("abs", 5).sql() 'ABS(5)'>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql() 'CAST(5 AS DOUBLE)'
Arguments:
- name: the name of the function to build.
- args: the args used to instantiate the function of interest.
- dialect: the source dialect.
- kwargs: the kwargs used to instantiate the function of interest.
Note:
The arguments
argsandkwargsare mutually exclusive.
Returns:
An instance of the function of interest, or an anonymous function, if
namedoesn't correspond to an existingsqlglot.expressions.Funcclass.
5172def true(): 5173 """ 5174 Returns a true Boolean expression. 5175 """ 5176 return Boolean(this=True)
Returns a true Boolean expression.
5179def false(): 5180 """ 5181 Returns a false Boolean expression. 5182 """ 5183 return Boolean(this=False)
Returns a false Boolean expression.
Returns a Null expression.